Java Reference
In-Depth Information
y
y
Symbol>='A'?
Symbol<='Z'?
It is a capital letter
n
n
else
y
y
Symbol>='a'?
Symbol<='z'?
It is a lower case letter
n
n
else
else
else
It is not a letter
It is not a letter
It is not a letter
We have four
if
statements altogether. The first
if
tests whether
symbol
is '
A
' or greater. If it is, it
could be a capital letter, a small letter, or possibly something else. But if it isn't, it is not a letter at all, so
the
else
for this
if
statement (towards the end of the program) produces a message to that effect.
The nested
if
statement, which is executed if
symbol
is '
A
' or greater, tests whether it is '
Z
' or less. If it
is, then
symbol
definitely contains a capital letter and the appropriate message is displayed. If it isn't
then it may be a small letter, so another
if
statement is nested within the
else
clause of the first nested
if
, to test for this possibility.
The
if
statement in the
else
clause tests for
symbol
being greater than '
a
'. If it isn't, we know that
symbol
is not a letter and a message is displayed. If it is, another
if
checks whether
symbol
is '
z
' or
less. If it is we have a small letter, and if not we don't have a letter at all.
You will have to run the example a few times to get all the possible messages to come up. They all will
- eventually.
Having carefully crafted our convoluted and cumbersome condition checking, now's the time to reveal
that there is a much easier way to achieve the same result.
Logical Operators
The tests we have put in the
if
expressions have been relatively simple so far, except perhaps for the
last one. Real life is typically more complicated. You will often want to combine a number of conditions
so that you execute a particular course, for example, if they are all
true
simultaneously. You can ride
the roller coaster if you are over 12 years old, over four feet tall,
and
less than six feet six. Failure on any
count and it's no go. Sometimes, though, you may need to test for any one of a number of conditions
being
true
, for example, you get a lower price entry ticket if you are under 16, or over 65.