Programming and Problem Solving with Java

(やまだぃちぅ) #1

(^176) | Selection and Encapsulation
else if(temperature > 70)
message = message + "tennis.";
else if(temperature > 32)
message = message + "golf.";
else if(temperature > 0)
message = message + "skiing.";
else
message = message + "dancing.";
System.out.println(message);
To see how this if-else-ifstructure works, consider the branch that tests for temperature
greater than 70. If it has been reached, we know that temperaturemust be less than or equal
to 85 because that condition causes this particular elsebranch to be taken. Thus, we need
to test only whether temperatureis above the bottom of this range (> 70). If that test fails, then
we enter the next elseclause knowing that temperaturemust be less than or equal to 70. Each
successive branch checks the bottom of its range until we reach the final else, which takes
care of all the remaining possibilities.
If the ranges aren’t consecutive, of course, we must test the data value against both the
highest and lowest value of each range. We still use an if-else-ifbecause it is the best struc-
ture for selecting a single branch from multiple possibilities, and we may arrange the ranges
in consecutive order to make them easier for a human reader to follow. But, in fact, we can-
not reduce the number of comparisons when there are gaps between the ranges.


The Dangling else


When ifstatements are nested, you may find yourself confused about the if-elsepairings.
That is, to which ifdoes an elsebelong? For example, suppose that if a student’s average is
below 60, we want to display “Failing”; if it is at least 60 but less than 70, we want to display
“Passing but marginal”; and if it is 70 or greater, we don’t want to display anything.
We code this information with an if-elsenested within an if:

if (average < 70.0)
if (average < 60.0)
System.out.println("Failing");
else
System.out.println("Passing but marginal");

How do we know to which ifthe elsebelongs? Here is the rule that the Java compiler fol-
lows: In the absence of braces, an elseis always paired with the closest preceding ifthat
doesn’t already have an elsepaired with it. We indented the code to reflect this pairing.
Suppose we write the fragment like this:

if (average >= 60.0) // Incorrect version
if (average < 70.0)
System.out.println("Passing but marginal");
else
System.out.println("Failing");
Free download pdf