Java Reference
In-Depth Information
The following is a sample log of the program execution:
Try to guess my two-digit
number, and I'll tell you how
many digits from your guess
appear in my number.
Your guess? 13
Incorrect (hint: 0 digits match)
Your guess? 26
Incorrect (hint: 0 digits match)
Your guess? 78
Incorrect (hint: 1 digits match)
Your guess? 79
Incorrect (hint: 1 digits match)
Your guess? 70
Incorrect (hint: 2 digits match)
Your guess? 7
You got it right in 6 tries.
Final Robust Version
The last major change we'll make to our program is to make it robust against invalid
user input. There are two types of bad input that we may see:
1. Nonnumeric tokens.
2. Numbers outside the range of 0-99.
Let's deal with these cases one at a time. Recall the getInt method that was dis-
cussed earlier in this chapter. It repeatedly prompts the user for input until an integer
is typed. Here is its header:
public static int getInt(Scanner console, String prompt)
We can make use of getInt to get an integer between 0 and 99. We'll repeatedly
call getInt until the integer that is returned is within the acceptable range. The post-
condition we require before we can stop prompting for guesses is:
guess >= 0 && guess <= 99
To ensure that this postcondition is met, we can use a while loop that tests for the
opposite condition. Using De Morgan's law, we know that the opposite of the previ-
ous test would be the following:
guess < 0 || guess > 99
 
Search WWH ::




Custom Search