Repeat Instructions: Java while Statements

By Barry Burd

Here’s a guessing game for you to test out your understanding of Java. The computer generates a random number from 1 to 10. The computer asks you to guess the number. If you guess incorrectly, the game continues. As soon as you guess correctly, the game is over. This listing shows the program to play the game, and the figure shows a round of play.

A round of a game created on Java.

import static java.lang.System.out;
import java.util.Scanner;
import java.util.Random;
public class GuessAgain {
    public static void main(String args[]) {
        Scanner keyboard = new Scanner(System.in);
        int numGuesses = 0;
        int randomNumber = new Random().nextInt(10) + 1;
        out.println("       ************         ");
        out.println("Welcome to the Guessing Game");
        out.println("       ************         ");
        out.println();
        out.print("Enter an int from 1 to 10: ");
        int inputNumber = keyboard.nextInt();
        numGuesses++;
        while (inputNumber != randomNumber) {
            out.println();
            out.println("Try again...");
            out.print("Enter an int from 1 to 10: ");
            inputNumber = keyboard.nextInt();
            numGuesses++;
        }
        out.print("You win after ");
        out.println(numGuesses + " guesses.");
        keyboard.close();
    }
}

In the figure, the user makes four guesses. Each time around, the computer checks to see whether the guess is correct. An incorrect guess generates a request to try again. For a correct guess, the user gets a rousing You win, along with a tally of the number of guesses he or she made.

The computer repeats several statements, checking each time through to see whether the user’s guess is the same as a certain randomly generated number. Each time the user makes a guess, the computer adds 1 to its tally of guesses. When the user makes the correct guess, the computer displays that tally. The figure illustrates the flow of action.

The flow of action in a game created on Java.

When you look over the listing, you see the code that does all this work. At the core of the code is a thing called a while statement (also known as a while loop). Rephrased in English, the while statement says:

while the inputNumber is not equal to the randomNumber
keep doing all the stuff in curly braces: {
}

The stuff in curly braces (the stuff that repeats) is the code that prints Try again and Enter an int . . ., gets a value from the keyboard, and adds 1 to the count of the user’s guesses.

When you’re dealing with counters, like numGuesses in the listing, you may easily become confused and be off by 1 in either direction. You can avoid this headache by making sure that the ++ statements stay close to the statements whose events you’re counting.

For example, in the listing, the variable numGuesses starts with a value of 0. That’s because, when the program starts running, the user hasn’t made any guesses. Later in the program, right after each call to keyboard.nextInt, is a numGuesses++ statement. That’s how you do it — you increment the counter as soon as the user enters another guess.

The statements in curly braces are repeated as long as inputNumber != randomNumber is true. Each repetition of the statements in the loop is called an iteration of the loop. In the figure, the loop undergoes three iterations. (If you don’t believe that the figure has exactly three iterations, count the number of Try again printings in the program’s output. A Try again appears for each incorrect guess.)

When, at long last, the user enters the correct guess, the computer goes back to the top of the while statement, checks the condition in parentheses, and finds itself in double double-negative land. The not equal (!=) relationship between inputNumber and randomNumber no longer holds.

In other words, the while statement’s condition, inputNumber != randomNumber, is false. Because the while statement’s condition is false, the computer jumps past the while loop and goes on to the statements just below the while loop. In these two statements, the computer prints You win after 4 guesses.

With code of the kind shown in the listing, the computer never jumps out in mid-loop. When the computer finds that inputNumber isn’t equal to randomNumber, the computer marches on and executes all five statements inside the loop’s curly braces. The computer performs the test again (to see whether inputNumber is still not equal to randomNumber) only after it fully executes all five statements in the loop.