Java Reference
In-Depth Information
The combination of
if/else
and
return
is powerful. It allows you to solve many
complex problems in the form of a method that accepts some input and computes a
result. But you have to be careful to think about the different paths that exist in the
code that you write. At first this process might seem annoying, but when you get the
hang of it, you will find that it allows you to simplify your code.
For example, suppose that we want to convert scores on the SAT into a rating to be
used for college admission. Each of the three components of the SAT ranges from
200 to 800, so the overall total ranges from 600 to 2400. Suppose that a hypothetical
college breaks up this range into three subranges with totals below 1200 considered
not competitive, scores of at least 1200 but less than 1800 considered competitive,
and scores of 1800 to 2400 considered highly competitive.
Let's write a method called
rating
that will take the total SAT score as a parame-
ter and will return a string with the appropriate text. We can use the AND operator
described earlier to write an
if/else
construct that has tests for each of these
ranges:
public static String rating(int totalSAT) {
if (totalSAT >= 600 && totalSAT < 1200) {
return "not competitive";
} else if (totalSAT >= 1200 && totalSAT < 1800) {
return "competitive";
} else if (totalSAT >= 1800 && totalSAT <= 2400) {
return "highly competitive";
}
}
This method has been written in a logical manner with specific tests for each of
the three cases, but it doesn't compile. The compiler indicates at the end of the
method that there was a “missing return statement.” That seems odd because there are
three different
return
statements in this method. We have included a
return
for
each of the different cases, so why is there a compiler error?
When the compiler encounters a method that is supposed to return a value, it com-
putes every possible path through the method and makes sure that each path ends
with a call on
return
. The method we have written has four paths through it. If the
first test succeeds, then the method returns
"not competitive"
. Otherwise, if the
second test succeeds, then the method returns
"competitive"
. If both of those tests
fail but the third test succeeds, then the method returns
"highly competitive"
.
But what if all three tests fail? That case would constitute a fourth path that doesn't
have a
return
statement associated with it. Instead, we would reach the end of the
method without having returned a value. That is not acceptable, which is why the
compiler produces an error message.
It seems annoying that we have to deal with a fourth case because we know that
the total SAT score will always be in the range of 600 to 2400. Our code covers all of
Search WWH ::
Custom Search