Академический Документы
Профессиональный Документы
Культура Документы
The program uses the method random of the class Math to generate a random number. To be specific, the expression: Math.random()returns a
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 visible 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.
import java.util.*;
while(!done) //Line3
{ //Line4
System.out.println(“Enter an integer greater than or equal to 0 and less than 100: ”); //Line5
guess = console.nextInt(); //Line6
System.out.println(); //Line7
if(guess==num) //Line8
{ //Line9
System.out.println(“You guessed the correct number.”); //Line10
done=true; //Line11
} //Line12
else if (guess < num){ //Line13
System.out.println(“Your guess is lower than the number.\n Guess again.”); //Line14
}else //Line15
System.out.println(“Your guess is higher than the number.\n Guess again.”); //Line16
}//end while //Line17
} //Line18
}
Sample runs:
The preceding program works as follows: The statement in Line1 creates an integer greater than or equal to 0 and less than 100 and stores this number
in the variable num. The statement in Line2 sets the boolean variable done to false. The while loop starts at Line3 and ends at Line17. The
expression in the while loop at Line3 evaluates the expression !done. if done is false, then !done is true and the body of the while loop
executes; if done is true, then !done is false, so the while loop terminates.
The statement in Line5 prompts the user to enter an integer greater than or equal to 0 and less than 100. The statement in Line6 stores the number
entered by the user in the variable guess. The expression in the if statement in Line8 determines whether the value of guess is the same as num, that
is, if the user guessed the number correctly. If the value of guess is the same as num, then the statements in Lines 10 and 11 execute. The statement in
Line 10 outputs the message:
The statement in Line11 sets the variable done to true. The control then goes back to Line3. Because done is true, !done is false and the while
loop terminates.
If the expression in Line8 evaluates to false, then the else statement in Line13 executes. The statement part of this else is an if..else statement,
starting at Line13 and ending at Line16. The if statement in Line13 determines whether the value of guess is less than num. in this case, the statement
in Line14 outputs the message:
If the expression in the if statement in Line13 evaluates to false, then the statement in Line16 executes, which outputs the message:
The program then prompts the user to enter an integer greater than or equal to 0 and less than 100.