Java Reference
In-Depth Information
do{
true
} while (condition);
false
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.
1
import
java . util .
;
∗
2
public class
Grade
{
3
public static void
main(String [] args)
{
4
int
x=(
int
)
(Math . random ( )
10) ;
∗
5
int
y=(
int
)
(Math . random ( )
10) ;
∗
6
Scanner keyboard =
new
Scanner(System. in) ;
7
do
{
8
System . out . p r i n t ( x +
"*"
+y+
"="
);
9
int
z = keyboard . nextInt () ;
10
}
while
(z!=x
∗
y);
11
System . out . p r i n t l n (
"This is correct!"
);
12
}
13
}
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
...
}