Programming and Problem Solving with Java

(やまだぃちぅ) #1
4.4 Nested if Statements | 173

This code does exactly what the tax form says it should: First it computes the result of sub-
tracting line 23 from line 17. Then it checks whether resultis less than zero. If it is, the frag-
ment displays a message telling the user to check box 24A and sets resultto zero. Finally, the
calculated result (or zero, if resultis less than zero) is stored into a variable named line24.
What happens if we leave out the left and right braces in the code fragment? Let’s look at it:


result = line17 – line23; // Incorrect version
if (result < 0.0)
System.out.println("Check box 24A");
result = 0.0;
line24 = result;


Despite the way we have indented the code, the compiler assumes that the first clause is a
single statement—the output statement. Ifresultis less than zero, the computer executes
the output statement, setsresultto zero, and then storesresultintoline24. So far, so good.
But ifresultis initially greater than or equal to zero, the computer skips the first clause and
proceeds to the statement following theifstatement—the assignment statement that sets
resultto zero. The unhappy outcome is thatresultends up as zero no matter what its initial
value was! The moral here is not to rely on indentation alone; you can’t fool the compiler. If
you want a compound statement for either clause, you must include the left and right braces.


4.4 Nested if Statements


Java does not place any restrictions on what the statements in an ifcan be. Therefore, an if
within an ifis okay. In fact, an ifwithin an ifwithin an ifis legal. The only limitation here is
that people cannot follow a structure that is too involved. Of course, readability is one of the
hallmarks of a good program.
When we place an ifwithin an if, we are creating a nested control structure. Control struc-
tures nest much like mixing bowls do, with smaller ones tucked inside larger ones. Here’s an
example, written in pseudocode:


if today is Saturday or Sunday

if it is raining
Sleep late
else
Get up and go outside

else
Go to work

Outer if

Inner (nested) if
Free download pdf