Java Reference
In-Depth Information
5.6 Case Study: NumberGuess
If we combine indefinite loops, the ability to check for user errors, and random number
generation, it's possible for us to create guessing games in which the computer thinks
of random numbers and the user tries to guess them. Let's consider an example game
with the following rules. The computer thinks of a random two-digit number but keeps
it secret from the player. We'll allow the program to accept positive numbers only, so
the acceptable range of numbers is 00 through 99 inclusive. The player will try to guess
the number the computer picked. If the player guesses correctly, the program will
report the number of guesses that the player made.
To make the game more interesting, the computer will give the player a hint each
time the user enters an incorrect guess. Specifically, the computer will tell the player
how many digits from the guess are contained in the correct answer. The order of the
digits doesn't affect the number of digits that match. For example, if the correct number
is 57 and the player guesses 73 , the computer will report one matching digit, because
the correct answer contains a 7 . If the player next guesses 75 , the computer will report
two matching digits. At this point the player knows that the computer's number must be
57 , because 57 is the only two-digit number whose digits match those of 75 .
Since the players will be doing a lot of console input, it's likely that they will type
incorrect numbers or nonnumeric tokens by mistake. We'd like our guessing-game
program to be robust against user input errors.
Initial Version without Hinting
In previous chapters, we've talked about the idea of iterative enhancement. Since this
is a challenging program, we'll tackle it in stages. One of the hardest parts of the pro-
gram is giving correct hints to the player. For now, we'll simply write a game that tells
players whether they are correct or incorrect on each guess and, once the game is
done, reports the number of guesses the players made. The program won't be robust
against user input errors yet; that can be added later. To further simplify the game,
rather than having the computer choose a random number, we'll choose a known value
for the number so that the code can be tested more easily.
Since we don't know how many tries a player will need before correctly guessing
the number, it seems that the main loop for this game will have to be a while loop. It
might be tempting to write the code to match the following pseudocode:
// flawed number guess pseudocode
think of a number.
while (user has not guessed the number) {
prompt and read a guess.
report whether the guess was correct or incorrect.
}
 
Search WWH ::




Custom Search