Java Reference
In-Depth Information
The following sample log of execution demonstrates the new input robustness of
this program:
Try to guess my two-digit
number, and I'll tell you how
many digits from your guess
appear in my number.
Your guess?
12
Incorrect (hint: 0 digits match)
Your guess?
okay
Not an integer; try again.
Your guess?
34
Incorrect (hint: 1 digits match)
Your guess?
35
Incorrect (hint: 1 digits match)
Your guess?
67
Incorrect (hint: 0 digits match)
Your guess?
89
Incorrect (hint: 0 digits match)
Your guess?
3
Incorrect (hint: 2 digits match)
Your guess?
300
Out of range; try again.
Your guess?
30
You got it right in 7 tries.
Notice that we're careful to comment our code to document relevant preconditions
and postconditions of our methods. The precondition of the
matches
method is that
the two parameters are unique two-digit numbers. The postcondition of our new
getGuesses
method is that it returns a guess between 0 and 99 inclusive. Also, note
that the program does not count invalid input (
okay
and
300
in the previous sample
log of execution) as guesses.
Chapter Summary
Java has a
while
loop in addition to its
for
loop. The
while
loop can be used to write indefinite loops that keep
executing until some condition fails.
Java can generate pseudorandom numbers using objects of
the
Random
class.
The
do/while
loop is a variation on the
while
loop that
performs its loop test at the end of the loop body. A
do/while
loop is guaranteed to execute its body at least
once.
Priming a loop means setting the values of variables that
will be used in the loop test, so that the test will be sure to
succeed the first time and the loop will execute.
Search WWH ::
Custom Search