Java Reference
In-Depth Information
The reversed test is used in our new getGuess method to get a valid guess
between 0 and 99. Now whenever we want to read user input in the main program,
we'll call getGuess . It's useful to separate the input prompting in this way, to make
sure that we don't accidentally count invalid inputs as guesses.
The final version of our code is the following:
1 // Robust two-digit number-guessing game with hinting.
2 import java.util.*;
3
4 public class NumberGuess3 {
5 public static void main(String[] args) {
6 giveIntro();
7 Scanner console = new Scanner(System.in);
8
9 // pick a random number from 0 to 99 inclusive
10 Random rand = new Random();
11 int number = rand.nextInt(100);
12
13 // get first guess
14 int guess = getGuess(console);
15 int numGuesses = 1;
16
17 // give hints until correct guess is reached
18 while (guess != number) {
19 int numMatches = matches(number, guess);
20 System.out.println("Incorrect (hint: " +
21 numMatches + " digits match)");
22 guess = getGuess(console);
23 numGuesses++;
24 }
25
26 System.out.println("You got it right in " +
27 numGuesses + " tries.");
28 }
29
30 public static void giveIntro() {
31 System.out.println("Try to guess my two-digit");
32 System.out.println("number, and I'll tell you how");
33 System.out.println("many digits from your guess");
34 System.out.println("appear in my number.");
35 System.out.println();
36 }
37
38 // returns # of matching digits between the two numbers
Search WWH ::




Custom Search