Java Reference
In-Depth Information
Table 4.7
Weight Status by BMI
BMI
Weight status
below 18.5
underweight
18.5-24.9
normal
25.0-29.9
overweight
30.0 and above
obese
In the sample execution we also see a report of the person's weight status. The CDC
website includes the information shown in Table 4.7. There are four entries in this table,
so we need four different
println
statements for the four possibilities. We will want to
use
if
or
if/else
statements to control the four
println
statements. In this case, we
know that we want to print exactly one of the four possibilities. Therefore, it makes
most sense to use a nested
if/else
construct that ends with an
else
.
But what tests do we use for the nested
if/else
? If you look closely at Table 4.7,
you will see that there are some gaps. For example, what if your BMI is 24.95? That
number isn't between 18.5 and 24.9 and it isn't between 25.0 and 29.9. It seems clear
that the CDC intended its table to be interpreted slightly differently. The range is
probably supposed to be 18.5-24.999999 (repeating), but that would look rather odd
in a table. In fact, if you understand nested
if/else
statements, this is a case in
which a nested
if/else
construct expresses the possibilities more clearly than a
table like the CDC's. The nested
if/else
construct looks like this:
if (bmi1 < 18.5) {
System.out.println("underweight");
} else if (bmi1 < 25) {
System.out.println("normal");
} else if (bmi1 < 30) {
System.out.println("overweight");
} else { // bmi1 >= 30
System.out.println("obese");
}
So, putting all this together, we get a complete version of the first program:
1
import
java.util.*;
2
3
public class
BMI1 {
4
public static void
main(String[] args) {
5
Scanner console =
new
Scanner(System.in);
6
7
System.out.println("Enter next person's information:");
8
System.out.print("height (in inches)? ");
Search WWH ::
Custom Search