Java Reference
In-Depth Information
Before we leave this example, it is worth thinking about what happens when the
method is passed an illegal SAT total. If it is passed a total less than 600, then it
classifies it as not competitive and if it passed a total greater than 2400, it will clas-
sify it as highly competitive. Those aren't bad answers for the program to give, but
the right thing to do is to document the fact that there is a precondition on the total.
In addition, we can add an extra test for this particular case and throw an exception
if the precondition is violated. Testing for the illegal values is a case in which the
logical OR is appropriate because illegal values will either be too low or too high
(but not both):
// pre: 600 <= totalSAT <= 2400 (throws IllegalArgumentException if not)
public static String rating(int totalSAT) {
if (totalSAT < 600 || totalSAT > 2400) {
throw new IllegalArgumentException("total: " + totalSAT);
} else if (totalSAT < 1200) {
return "not competitive";
} else if (totalSAT >= 1800) {
return "highly competitive";
} else { // 1200 <= totalSAT < 1800
return "competitive";
}
}
4.5 Case Study: Body Mass Index
Individual body mass index has become a popular measure of overall health. The
Centers for Disease Control and Prevention (CDC) website about body mass index
(http://www.cdc.gov/healthyweight/assessing/bmi/index.html) explains:
Body Mass Index (BMI) is a number calculated from a person's weight and
height. BMI provides a reliable indicator of body fatness for most people and
is used to screen for weight categories that may lead to health problems.
It has also become popular to compare the statistics for two or more individuals
who are pitted against one another in a “fitness challenge,” or to compare two sets of
numbers for the same person to get a sense of how that person's BMI will vary if a
person loses weight. In this section, we will write a program that prompts the user for
the height and weight of two individuals and reports the overall results for the two
people. Here is a sample execution for the program we want to write:
This program reads data for two
people and computes their body
mass index and weight status.
 
Search WWH ::




Custom Search