Java Reference
In-Depth Information
while (condition) {
true
false
}
FIGURE 3.1: The while construct.
14
}
}
15
In the new code, we will eliminate Lines 9-13. We will execute Lines 7-8 multiple times
until the correct answer is given by the user. Lines that need to be executed multiple times
can be surrounded by a while block. The new code for Lines 7-8 is shown next.
int z;
while (...) {
System. out . print (x + "*" +y+ "=" );
z = keyboard . nextInt () ;
}
If the condition in the while statement parentheses is true, then the while statement
block is executed. Otherwise, the block is skipped and the program continues executing
with the first line after the while block; see Figure 3.1.
A while statement allows the same block that is surrounded by braces to be
repeatedly executed. The block can be executed zero or more times. The program will
stop repeatedly executing the block and move to the line immediately after the block
when the condition inside the parentheses of the while statement becomes false .
In other words, we need to have a condition that should be true when we want to
execute the block and should become false when we want to move on. Maybe in our case
we can rewrite the code as follows.
int z;
while (z!=x
{
System. out . print (x + "+" +y+ "=" );
z = keyboard . nextInt () ;
y)
}
If z is not equal to x*y , then this means that the user did not answer the question
correctly. In this case, we will go ahead and ask them for input again. The only remaining
caveat is that we need to insure that the while statement is executed at least once. We
can assure that by setting the variable z initially to a value that is different from x*y .The
rewritten program follows.
import java . util . ;
public class Arithmetic {
public static void main(String [] args)
{
 
Search WWH ::




Custom Search