Java Reference
In-Depth Information
But the problem with this pseudocode is that you can't start the while loop if you
don't have a guess value from the player yet. The following code doesn't compile,
because the variable guess isn't initialized when the loop begins:
// this code doesn't compile
int numGuesses = 0;
int number = 42; // computer always picks same number
int guess;
while (guess ! = number) {
System.out.print("Your guess? ");
guess = console.nextInt();
numGuesses++;
System.out.println("Incorrect.");
}
System.out.println("You got it right in " + numGuesses + " tries.");
It turns out that the game's main guess loop is a fencepost loop, because after each
incorrect guess the program must print an “Incorrect” message (and later a hint). For n
guesses, there are n - 1 hints. Recall the following general pseudocode for fencepost
loops:
plant a post.
for (the length of the fence) {
attach some wire.
plant a post.
}
This particular problem is an indefinite fencepost using a while loop. Let's look
at some more specific pseudocode. The “posts” are the prompts for guesses, and the
“wires” are the “Incorrect” messages:
// specific number guess pseudocode
think of a number.
ask for the player's initial guess.
while (the guess is not the correct number) {
inform the player that the guess was incorrect.
ask for another guess.
}
report the number of guesses needed.
Search WWH ::




Custom Search