Java Reference
In-Depth Information
We need to be able to split the correct number and the guess into the two digits
that compose each so that we can compare them. Recall from the Boolean Zen sec-
tion that we can use the division and remainder operators to express the digits of any
two-digit number n as n/10 for the tens digit and n%10 for the ones digit.
Let's write the statement that compares the tens digit of the guess against the cor-
rect answer. Since the tens digit of the guess can match either of the correct number's
digits, we'll use an OR test with the || operator:
int matches = 0;
// check the first digit for a match
if (guess / 10 == number / 10 || guess / 10 == number % 10) {
matches++;
}
Writing the statement that compares the ones digit of the guess against the correct
answer is slightly trickier, because we have to take into consideration the special case
described previously (in which both digits of the guess are the same). We'll account
for this by counting the second digit as a match only if it is unique and matches a
digit from the correct number:
// check the second digit for a match
if (guess / 10 ! = guess % 10 &&
(guess % 10 == number / 10 || guess % 10 == number % 10)) {
matches++;
}
The following version of the program uses the hinting code we've just written. It
also adds the randomly chosen number and a brief introduction to the program:
1 // Two-digit number-guessing game with hinting.
2 import java.util.*;
3
4 public class NumberGuess2 {
5 public static void main(String[] args) {
6 System.out.println("Try to guess my two-digit");
7 System.out.println("number, and I'll tell you how");
8 System.out.println("many digits from your guess");
9 System.out.println("appear in my number.");
10 System.out.println();
11
12 Scanner console = new Scanner(System.in);
13
14 // pick a random number from 0 to 99 inclusive
Search WWH ::




Custom Search