Java Reference
In-Depth Information
} while (condition);
FIGURE 3.2: The do-while construct.
A do-while statement is similar to a while statement. The difference is that a
do-while statement is always executed at least once. The while statement is at the
end of the block and is followed by a semicolon.
Note that one may be tempted to rewrite the code as follows.
import java . util .
2 public class Grade
public static void main(String [] args)
int x=( int )
(Math . random ( )
10) ;
int y=( int )
(Math . random ( )
10) ;
Scanner keyboard = new Scanner(System. in) ;
do {
System . out . p r i n t ( x + "*" +y+ "=" );
int z = keyboard . nextInt () ;
} while (z!=x y);
System . out . p r i n t l n ( "This is correct!" );
This, however, is the wrong approach and the rewrite will generate a compiler error. The
reason is that every variable has a scope. The scope of a variable is defined by the inner-
most block (opening-closing braces) where the variable is defined. In the above example,
the variable z is not defined after the closing brace at Line 10 and therefore cannot be
referenced in the while condition.
Note that both the while and do-while loops can be applied on a single statement. For
example, consider the following code.
while ( true )System.out.println( "Hi" );
The code will keep printing Hi indefinitely. Although creating such loops is possible, this
is a bad programming practice because it is error prone. For example, if we want the loop
to print two lines, we may modify the code as follows.
while ( true )
System. out . println ( "Hi" );
System. out . println ( "What is your name? " );
However, the while statement applies only on the first line and the second print state-
ment will never be executed.
The astute reader may wonder what the reason is for allowing the statement
while(true) {
. Does this not mean that the loop will continue executing forever?
The answer is no. One can insert inside a while block the break statement. It causes the
Search WWH ::

Custom Search