Java Reference
In-Depth Information
39 // pre: number and guess are unique two-digit numbers
40
public static int
matches(
int
number,
int
guess) {
41
int
numMatches = 0;
42
43
if
(guess / 10 == number / 10 ||
44 guess / 10 == number % 10) {
45 numMatches++;
46 }
47
48
if
(guess / 10 ! = guess % 10 &&
49 (guess % 10 == number / 10 ||
50 guess % 10 == number % 10)) {
51 numMatches++;
52 }
53
54
return
numMatches;
55 }
56
57 // prompts until a number in proper range is entered
58 // post: guess is between 0 and 99
59
public static int
getGuess(Scanner console) {
60
int
guess = getInt(console, "Your guess? ");
61
while
(guess < 0 || guess >= 100) {
62 System.out.println("Out of range; try again.");
63 guess = getInt(console, "Your guess? ");
64 }
65
66
return
guess;
67 }
68
69 // prompts until a valid number is entered
70
public static int
getInt(Scanner console, String prompt) {
71 System.out.print(prompt);
72
while
(!console.hasNextInt()) {
73 console.next(); // to discard the input
74 System.out.println("Not an integer; try again.");
75 System.out.print(prompt);
76 }
77
return
console.nextInt();
78 }
79 }
Search WWH ::
Custom Search