Java Reference
In-Depth Information
program to jump to the line immediately after the while statement regardless of the value
of the while condition. For example, our multiplication program can be rewritten as follows.
import java . util . ;
public class Arithmetic {
public static void main(String [] args)
{
int x=( int ) (Math . random ( ) 10) ;
int y=( int ) (Math . random ( ) 10) ;
Scanner keyboard = new Scanner(System. in) ;
int z;
do System. out . print (x + "*" +y+ "=" );
z = keyboard . nextInt () ;
if (z==x
{
y)
break ;
}
{
System. out . println ( "This is incorrect!" );
else
}
} while ( true );
System. out . println ( "This is correct!" );
}
}
The program checks if the variable z is equal to x*y . If it is, the program breaks out of
the do-while statement. Otherwise, it prints that the guess was wrong and starts executing
the loop again. Note that the break statement can be used to escape from both while and
do-while loops and from a switch block. In general, the break statement can be used to
escape from any loop or a switch block. However, the break statement cannot be used to
escape from any other block, including an if block.
3.3 The for Loop
Next, let us play a guessing the game. The computer will think of a random number
between 0 and 999. We will have 10 tries to guess the number. Every time we guess, we
will be told if the number is lower or higher. In this program, we need to perform a task at
most 10 times. One way to do so is to use a while loop that keeps track of the number of
guesses. A break statement can be executed when the number is guessed before the tenth
try. Here is a code snippet of the program.
...
int numTries = 0;
while (numTries < =9) {
...
numTries = numTries+1;
} ...
The while statement will be executed for numTries = 0 to 9, that is, a total of 10 times.
In general, the easiest way to execute something 10 times is to create a counter that keeps
track of how many times it is executed. One needs a loop that keeps executing the block
until the counter reaches a predetermined value. This is similar to going to the gym and
running ten laps. You need to keep track of how many laps you have run and stop when this
 
Search WWH ::




Custom Search