Java Reference
In-Depth Information
The loop in lines 15-19 repeatedly prompts the user to enter an
answer
when
number1 +
number2 != answer
is
true
. Once
number1 + number2 != answer
is
false
, the loop
exits.
4.2.1 Case Study: Guessing Numbers
The problem is to guess what number a computer has in mind. You will write a program that
randomly generates an integer between
0
and
100
, inclusive. The program prompts the user to
enter a number continuously until the number matches the randomly generated number. For
each user input, the program tells the user whether the input is too low or too high, so the user
can make the next guess intelligently. Here is a sample run:
VideoNote
Guess a number
Guess a magic number between 0 and 100
Enter your guess:
Your guess is too high
Enter your guess:
Your guess is too low
Enter your guess:
Your guess is too high
Enter your guess:
Yes, the number is 39
50
25
42
39
The magic number is between
0
and
100
. To minimize the number of guesses, enter
50
first. If your guess is too high, the magic number is between
0
and
49
. If your guess is too low,
the magic number is between
51
and
100
. So, you can eliminate half of the numbers from fur-
ther consideration after one guess.
How do you write this program? Do you immediately begin coding? No. It is important to
think before coding.
Think how you would solve the problem without writing a program. You
need first to generate a random number between
0
and
100
, inclusive, then to prompt the user
to enter a guess, and then to compare the guess with the random number.
It is a good practice to
code incrementally
one step at a time. For programs involving loops,
if you don't know how to write a loop right away, you may first write the code for executing
the loop one time, and then figure out how to repeatedly execute the code in a loop. For this
program, you may create an initial draft, as shown in Listing 4.2.
intelligent guess
think before coding
code incrementally
L
ISTING
4.2
GuessNumberOneTime.java
1
import
java.util.Scanner;
2
3
public class
GuessNumberOneTime {
4
public static void
main(String[] args) {
5
// Generate a random number to be guessed
6
7
8 Scanner input =
new
Scanner(System.in);
9 System.out.println(
"Guess a magic number between 0 and 100"
);
10
11
// Prompt the user to guess the number
12 System.out.print(
"\nEnter your guess: "
);
13
14
15
16 System.out.println(
"Yes, the number is "
+ number);
17
18 System.out.println(
"Your guess is too high"
);
19
int
number = (
int
)(Math.random() *
101
);
generate a number
int
guess = input.nextInt();
enter a guess
if
(guess == number)
correct guess?
else if
(guess > number)
too high?
else