Program: Higher or Lower

Now we’ll write a program similar to the number guessing game in chapter 4. The program will “think” of a number between 1 and 100 and the user (player) will try to guess it; except this time the user will have infinite guesses. If the guess is too low, the program will respond “HIGHER” and if the guess is too high, the program will respond “LOWER”. When the user successfully guesses the number, the program will respond “CORRECT” and end.

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

public class HigherOrLower1 {
    public static void main(String[] args) {
        Scanner sc = new Scanner(;
        int target = ThreadLocalRandom.current().nextInt(1, 101);
        int guess;

        System.out.println("\n--- Guess My Number Game ---");

        do {
            System.out.print("\nGuess: ");
            guess = sc.nextInt();

            if (guess < target) {
            else if (guess > target) {
            else {
                System.out.println("CORRECT. My number was " + target + ".");
        } while (guess != target);

The two important variables here are target (line 7) and guess (line 8). Variable target will hold the target number. Variable guess will hold the user’s guess. Starting at the top, line 6 creates a Scanner. Line 7 generates a random number from 1 to 100, which goes in variable target. Line 8 declares variable guess. This variable is undefined at this point because it does not have a value. (Note that variables must be given a value before they are read otherwise you will get an error.) Line 10 prints the title of the game. Lines 12-25 is a do-while loop that will repeat until the user guesses the target number correctly. We can see this from the loop’s condition that says if the user’s guess does not equal the target, it will repeat. Before that, however, line 13 prompts the user for a guess and line 14 obtains it. Lines 16-24 are a three-block if statement. The first block checks if the user’s guess is less than the target number ( guess < target ), in which case the user has guessed too low and line 17 prints “HIGHER.” The second block checks if the user’s guess is greater than the target number ( guess > target ), in which case the user has guessed too high and line 20 prints “LOWER.” If neither are true then guess must equal target meaning the user wins and the else block prints “CORRECT. My number was target.” As mentioned, line 25 will only repeat the loop is guess does not equal target, resulting in another guess.

--- Guess My Number Game ---
Guess: 82
Guess: 56
Guess: 29
Guess: 38
Guess: 47
Guess: 50
Guess: 49
Guess: 48
CORRECT. My number was 48.

Leave a Reply

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