Java Reference
In-Depth Information
double height = console.nextDouble();
System.out.print("weight (in pounds)? ");
double weight = console.nextDouble();
double bmi = weight / (height * height) * 703;
System.out.println();
}
We have to pass in the Scanner from main . Otherwise we have made all the vari-
ables local to this method. From main we can call this method twice:
getBMI(console);
getBMI(console);
Unfortunately, introducing this change breaks the rest of the code. If we try to
compile and run the program, we find that we get error messages in main whenever
we refer to the variables bmi1 and bmi2 .
The problem is that the method computes a bmi value that we need later in the
program. We can fix this by having the method return the bmi value that it computes:
public static double getBMI(Scanner console) {
System.out.println("Enter next person's information:");
System.out.print("height (in inches)? ");
double height = console.nextDouble();
System.out.print("weight (in pounds)? ");
double weight = console.nextDouble();
double bmi = weight / (height * height) * 703;
System.out.println();
return bmi;
}
Notice that the method header now lists the return type as double . We also have to
change main . We can't just call the method twice the way we would call a void
method. Because each call returns a BMI result that the program will need later, for
each call we have to store the result coming back from the method in a variable:
double bmi1 = getBMI(console);
double bmi2 = getBMI(console);
Study this change carefully, because this technique can be one of the most chal-
lenging for novices to master. When we write the method, we have to make sure that
it returns the BMI result. When we write the call, we have to make sure that we store
the result in a variable so that we can access it later.
After this modification, the program will compile and run properly. But there is
another obvious redundancy in the main method: The same nested if/else con-
struct appears twice. The only difference between them is that in one case we use the
Search WWH ::




Custom Search