Java Reference
In-Depth Information
6.4 A Guessing Game
To illustrate a simple use of random numbers, let's write a program to play a guessing game. The program will “think”
of a number from 1 to 100. You are required to guess the number using as few guesses as possible. The following is a
sample run of the program. Underlined items are typed by the user:
I have thought of a number from 1 to 100.
Try to guess what it is.
Your guess? 50
Too low
Your guess? 75
Too high
Your guess? 62
Too high
Your guess? 56
Too low
Your guess? 59
Too high
Your guess? 57
Congratulations, you've got it!
As you can see, each time you guess, the program will tell you whether your guess is too high or too low and allow
you to guess again.
The program will “think” of a number from 1 to 100 by calling random(1, 100) . You will guess until you have
guessed correctly or until you give up. You give up by entering 0 as your guess. Program P6.2 contains all the details.
Program P6.2
import java.util.*;
public class GuessTheNumber {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.printf("\nI have thought of a number from 1 to 100.\n");
System.out.printf("Try to guess what it is.\n\n");
int answer = random(1, 100);
System.out.printf("Your guess? ");
int guess = in.nextInt();
while (guess != answer && guess != 0) {
if (guess < answer) System.out.printf("Too low\n");
else System.out.printf("Too high\n");
System.out.printf("Your guess? ");
guess = in.nextInt();
}
if (guess == 0) System.out.printf("Sorry, answer is %d\n", answer);
else System.out.printf("Congratulations, you've got it!\n");
} //end main
 
Search WWH ::




Custom Search