Java Reference
In-Depth Information
39
System.out.println("obese");
40
}
41
42
System.out.printf("Person #2 body mass index = %5.2f\n", bmi2);
43
if (bmi2 < 18.5) {
44
System.out.println("underweight");
45
} else if (bmi2 < 25) {
46
System.out.println("normal");
47
} else if (bmi2 < 30) {
48
System.out.println("overweight");
49
} else { // bmi2 >= 30
50
System.out.println("obese");
51
}
52
}
53 }
This program compiles and works. When we execute it, we get exactly the interaction
we wanted. However, the program lacks structure. All of the code appears in main , and
there is significant redundancy. That shouldn't be a surprise, because we created this ver-
sion by copying and pasting. Whenever you find yourself using copy and paste, you
should wonder whether there isn't a better way to solve the problem. Usually there is.
Two-Person Structured Solution
Let's explore how static methods can improve the structure of the program. Looking
at the code, you will notice a great deal of redundancy. For example, we have two
code segments that look like this:
System.out.println("Enter next person's information:");
System.out.print("height (in inches)? ");
double height1 = console.nextDouble();
System.out.print("weight (in pounds)? ");
double weight1 = console.nextDouble();
double bmi1 = weight1 / (height1 * height1) * 703;
System.out.println();
The only difference between these two code segments is that the first uses vari-
ables height1 , weight1 , bmi1 , and the second uses variables height2 , weight2 ,
and bmi2 . We eliminate redundancy by moving code like this into a method that we
can call twice. So, as a first approximation, we can turn this code into a more generic
form as the following method:
public static void getBMI(Scanner console) {
System.out.println("Enter next person's information:");
System.out.print("height (in inches)? ");
 
Search WWH ::




Custom Search