Java Reference
In-Depth Information
15 Random rand = new Random();
16 int number = rand.nextInt(100);
17
18 // get first guess
19 System.out.print("Your guess? ");
20 int guess = console.nextInt();
21 int numGuesses = 1;
22
23 // give hints until correct guess is reached
24 while (guess != number) {
25 int numMatches = matches(number, guess);
26 System.out.println("Incorrect (hint: " +
27 numMatches + " digits match)");
28 System.out.print("Your guess? ");
29 guess = console.nextInt();
30 numGuesses++;
31 }
32
33 System.out.println("You got it right in " +
34 numGuesses + " tries.");
35 }
36
37 // reports a hint about how many digits from the given
38 // guess match digits from the given correct number
39 public static int matches( int number, int guess) {
40 int numMatches = 0;
41
42 if (guess / 10 == number / 10 ||
43 guess / 10 == number % 10) {
44 numMatches++;
45 }
46
47 if (guess / 10 ! = guess % 10 &&
48 (guess % 10 == number / 10 ||
49 guess % 10 == number % 10)) {
50 numMatches++;
51 }
52
53 return numMatches;
54 }
55 }
Search WWH ::




Custom Search