As a more fun example, let’s write a number guessing game. The program picks a number from 1 to 5 and the player has to guess which number the program picked. How does a computer pick a number? By using a random number generator (RNG). There are two classes in Java that make this an easy task: Random and ThreadLocalRandom. To use Random we first have to create an object of it, like so:

Random random = new Random();
int number = random.nextInt(5) + 1;

On line 1, a Random object is created with code new Random(). On the left, a variable is declared to hold the object (again, Random (uppercase R) is the variable type and random (lowercase r) is the variable name). The equals (=) assigns the Random object to the random variable. On line 2, we call random.nextInt(5). The nextInt method generates a random number from 0 to whatever number the argument is, called the bound. In this case, it will generate a random number from 0 to 5. However, the bound is exclusive, meaning “up to but not including 5”. So really, it’ll generate either 0, 1, 2, 3, or 4. This is why there’s a + 1 on the end so we get 1, 2, 3, 4, or 5 instead. Whichever number is generated is then stored in variable number.

Alternatively, we can use ThreadLocalRandom. This class was designed to address performance issues when generating random numbers in multithreaded programs. Our programs don’t have this problem, but we can still use it.

int number = ThreadLocalRandom.current().nextInt(1, 6);

As we can see, the line calls ThreadLocalRandom.current(). The current method returns a pre-made ThreadLocalRandom object (meaning it’s not necessary to write new ThreadLocalRandom() to create a new one). On this object, the nextInt method is called, with 1 for the origin and 6 for the bound. The origin is inclusive but the bound is exclusive, meaning nextInt(1, 6) will generate and return a number from 1 to 5, not 1 to 6. The generated number is stored in variable number. It’s not overly important that you remember the details of this line of code. Just know that if you need random numbers in future programs, you can simply copy and paste it and change the numbers to suit.

Here is the first version of the game:

import java.util.Scanner;
import java.util.concurrent.ThreadLocalRandom;

public class NumberGuessingGame {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);

        int number = ThreadLocalRandom.current().nextInt(1, 6);
        System.out.println("I'm thinking of a number from 1 to 5. Try to guess it.");

        System.out.print("Your guess: ");
        int guess = scanner.nextInt();

        if (guess == number) {
            System.out.println("Correct! Aren't you lucky?");
        }
        else {
            System.out.println("Wrong! Maybe next time.");
        }
    }
}

Line 6 sets up the Scanner for input. Line 8 generates a random number from 1 to 5 and stores it in variable number. Line 9 prints an instructional message about how to play the game. Line 11 prompts the user for a guess. Line 12 retrieves the guess and stores it in variable guess. Line 14 checks if the user’s guess is equal to the random number. If true, line 15 prints that the user won. If false, line 18 prints that the user lost.

[Run 1]
I'm thinking of a number from 1 to 5. Try to guess it.
Your guess: 1
Wrong! Maybe next time.
[Run 2]
I'm thinking of a number from 1 to 5. Try to guess it.
Your guess: 1
Correct! Aren't you lucky?

Trying to win the game with only one guess is quite difficult as there’s only a 20% chance of success. Let’s up that chance to 40% by affording the user two guesses. This will involve nesting another if statement inside the existing one. Here is the relevant snippet of code.

if (guess == number) {
    System.out.println("Correct! Aren't you lucky?");
}
else {
    System.out.println("Wrong! Have another go.");
    System.out.print("Your guess: ");
    guess = scanner.nextInt();

    if (guess == number) {
        System.out.println("Correct! Good effort.");
    }
    else {
        System.out.println("Wrong again! Maybe next time.");
    }
}

In this version, code has been added to the else block (lines 4-15) to allow the user a second guess. Like before, if the condition on line 1 is false, meaning the user has guessed incorrectly, the else block will run. Line 5 informs the user they’re wrong but this time they can have another go. Line 6 asks for another guess. Line 7 obtains the user’s next guess and reassigns the guess variable to it. Lines 9-14 is an inner if statement that is basically a copy of the outer one. Line 9 checks if guess is equal to number. If true, line 10 prints that the user got it right, and if false, line 13 prints that the user got it wrong (again). Here are the three variants:

[Run 1]
I'm thinking of a number from 1 to 5. Try to guess it.
Your guess: 5
Correct! Aren't you lucky?
[Run 2]
I'm thinking of a number from 1 to 5. Try to guess it.
Your guess: 2
Wrong! Have another go.
Your guess: 5
Wrong again! Maybe next time.
[Run 3]
I'm thinking of a number from 1 to 5. Try to guess it.
Your guess: 4
Wrong! Have another go.
Your guess: 1
Correct! Good effort.

Leave a Reply

Your email address will not be published. Required fields are marked *