Java Reference
In-Depth Information
This program prompts the player and then reads a character from the keyboard. Using
an
if
statement, it then checks that character against the answer, which is K in this case. If
K was entered, the message is displayed. When you try this program, remember that the K
must be entered in uppercase.
Taking the guessing game further, the next version uses the
else
to print a message when
the wrong letter is picked.
Nested ifs
A
nested
if
is an
if
statement that is the target of another
if
or
else
. Nested
if
s are very com-
mon in programming. The main thing to remember about nested
if
s in Java is that an
else
statement always refers to the nearest
if
statement that is within the same block as the
else
and not already associated with an
else
. Here is an example:
As the comments indicate, the final
else
is not associated with
if(j < 20)
, because it is not
in the same block (even though it is the nearest
if
without an
else
). Rather, the final
else
is