Java Reference
In-Depth Information
The Programming Example Checking Account Balance, available with the Additional
Student Files at www.cengagebrain.com,
further illustrates how to use an EOF-controlled
while loop in a program.
More on Expressions in while Statements
In the examples in the previous sections, the expression in the while statement is quite
simple. In other words, the while loop is controlled by a single variable. However,
there are situations where the logical expression in the while statement may be more
complex.
For example, the program in Example 5-6 uses a flag-controlled while loop to imple-
ment the Guessing the Number game. However, the program gives as many tries as the
user needs to guess the number. Suppose you want to give the user, at most, five tries to
guess the number. If the user does not guess the number correctly within five tries, then
the program outputs the random number generated by the program, as well as a message
that they lost the game. In this case, you can write the while loop as follows. (Assume
that numOfGuesses is an int variable initialized to 0 .)
5
while ((numOfGuesses < 5) && (!done))
{
System.out.print ("Enter an integer greater "
+ "than or equal to 0 and "
+ "less than 100: ");
guess = console.nextInt();
System.out.println();
numOfGuesses++;
if (guess == num)
{
System.out.println("Winner!. You guessed the "
+ "correct number.");
done = true ;
}
else if (guess < num)
System.out.println("Your guess is "
+ "lower than "
+ "the number.\n"
+ "Guess again!");
else
System.out.println("Your guess is "
+ "higher than "
+ "the number.\n"
+ "Guess again!");
} //end while
 
Search WWH ::




Custom Search