Java Reference
In-Depth Information
int x=( int ) (Math . random ( ) 10) ;
int y=( int ) (Math . random ( ) 10) ;
Scanner keyboard = new Scanner(System. in) ;
int z=x y+1;
while (z!=x y) {
System. out . print (x + "*" +y+ "=" );
z = keyboard . nextInt () ;
System. out . println ( "This is correct!" );
}
}
Note the last printing statement in the code. It will only be executed when the while
condition becomes false. In other words, it will only be executed when z is equal to x*y .At
this point, we know that the user entered the correct guess and we can let them know.
3.2 The do-while Construct
In the previous code we needed to put in extra effort to ensure that the code in the
while block is executed at least once. Setting the value of z to x*y+1 is not an elegant
solution. This is a common scenario and giving fake values to variables in order to ensure
that the while loop is executed at least once is not the best option. Alternatively, we can
use a do-while loop, which ensures that the body of the loop is executed at least once.
Here is how the program can use the do-while statement.
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 () ;
} while (z!=x y);
System. out . println ( "This is correct!" );
}
}
One needs to insert a semicolon at the end of a do-while statement. This happens
to be the only Java construct that requires a semicolon at the end.
The structure of a do-while statement is shown in Figure 3.2. As the figure suggests, a
do-while statement works very similar to a while statement. When the condition is true,
the block is executed again. The block stops being executing when the condition becomes
false. The only major difference is that a do-while statement guarantees that the block is
executed at least once. A minor difference is that a do - while statement must always end
with a semicolon. Interestingly, this is the only Java structure that ends with a semicolon.
 
Search WWH ::




Custom Search