Java Reference
In-Depth Information
You also need the following code, to be included after the while loop, in case the user
cannot guess the correct number in five tries:
if (!done)
System.out.println("You lose! The correct "
+ "number is " + num);
We leave it as an exercise for you to write a complete Java program to implement the
Guessing the Number game in which the user has, at most, five tries to guess the number.
(See Programming Exercise 16 at the end of this chapter.)
As you can see from the preceding while loop, the logical expression in a while
statement can be complex. The main objective of a while loop is to repeat certain
statement(s) until certain conditions are met.
Next, consider the following while loop:
int count = 0;
while (count++ < 5)
System.out.println("Iteration: " + count);
System.out.println("The value of count after the while loop: " + count);
Note that the loop control variable count is initialized before the while loop and its
value is updated in the while loop test condition (logical expression). The expression
count++ < 5 uses the post-increment operator. So first the value of count is used to
evaluate the expression and then the value of count is incremented. The output of the
previous while loop is:
Iteration: 1
Iteration: 2
Iteration: 3
Iteration: 4
Iteration: 5
The value of count after the while loop: 6
Now consider the following while loop:
int count = 0;
while (++count < 5)
System.out.println("Iteration: " + count);
System.out.println("The value of count after the while loop: " + count);
In this while loop, the expression ++count < 5 uses the pre-increment operator. So first
the value of count is incremented and then its value is used to evaluate the expression.
The output of the previous while loop is:
Iteration: 1
Iteration: 2
Iteration: 3
Iteration: 4
The value of count after the while loop: 5
Search WWH ::




Custom Search