Java Reference
In-Depth Information
Example 5-6 further illustrates the use of a flag-controlled
while
loop.
EXAMPLE 5-6 GUESSING THE NUMBER GAME
The following program randomly generates an integer greater than or equal to
0
and less
than
100
. The program then prompts the user to guess the number. If the user guesses the
number correctly, the program outputs an appropriate message. Otherwise, the program
checks whether the guessed number is less than the random number. If the guessed
number is less than the random the number generated by the program, the program
outputs the message, ''Your guess is lower than the number''; otherwise, the program
outputs the message, ''Your guess is higher than the number''. The program then
prompts the user to enter another number. The user is prompted to guess the random
number until the user enters the correct number.
The program uses the method
random
of the
class
Math
to generate a random number.
To be specific, the expression:
Math.random()
returns a value of type
double
greater than or equal to
0.0
and less than
1.0
. To convert
it to an integer greater than or equal to
0
and less than
100
, the program uses the
following expression:
(
int
) (Math.random() * 100);
Furthermore, the program uses the
boolean
variable
done
to control the loop. The
boolean
variable
done
is initialized to
false
. It is set to
true
when the user guesses the
correct number.
//Flag-controlled while loop.
//Guessing the number game.
import
java.util.*;
public class
FlagControlledLoop
{
static
Scanner console =
new
Scanner(System.in);
public static void
main(String[] args)
{
//declare the variables
int
num;
//variable to store the random number
int
guess;
//variable to store the number
//guessed by the user
boolean
done;
//boolean variable to control the loop
num = (
int
) (Math.random() * 100);
//Line 1
done =
false
;
//Line 2
while
(!done)
//Line 3
{
//Line 4
Search WWH ::
Custom Search