Java Reference
In-Depth Information
variable bmi1 , and in the other case we use the variable bmi2 . The construct is easily
generalized with a parameter:
public static void reportStatus(double bmi) {
if (bmi < 18.5) {
System.out.println("underweight");
} else if (bmi < 25) {
System.out.println(“normal");
} else if (bmi < 30) {
System.out.println("overweight");
} else { // bmi >= 30
System.out.println("obese");
}
}
Using this method, we can replace the code in main with two calls:
System.out.printf("Person #1 body mass index = %5.2f\n", bmi1);
reportStatus(bmi1);
System.out.printf("Person #2 body mass index = %5.2f\n", bmi2);
reportStatus(bmi2);
That change takes care of the redundancy in the program, but we can still use static
methods to improve the program by better indicating structure. It is best to keep the
main method short if possible, to reflect the overall structure of the program. The prob-
lem breaks down into three major phases: introduction, the computation of the BMI,
and the reporting of the results. We already have a method for computing the BMI, but
we haven't yet introduced methods for the introduction and reporting of results. It is
fairly simple to add these methods.
There is one other method that we should add to the program. We are using a for-
mula from the CDC website for calculating the BMI of an individual given the per-
son's height and weight. Whenever you find yourself programming a formula, it is a
good idea to introduce a method for that formula so that it is easy to spot and so that
it has a name.
Applying all these ideas, we end up with the following version of the program:
1 // This program finds the body mass index (BMI) for two
2 // individuals. This variation includes several methods
3 // other than main.
4
5 import java.util.*;
6
7 public class BMI3 {
8
public static void main(String[] args) {
9
giveIntro();
Search WWH ::




Custom Search