Java Reference
In-Depth Information
To calculate the value of this expression, the computer divides the weight by the
square of the height and then multiplies the result of that operation by the literal
value 703 . The result is stored in the variable bmi . So, after the computer has exe-
cuted the third assignment statement, the memory looks like this:
height 70.0
weight 195.0
bmi 27.976530612244897
The last two lines of the program report the BMI result using println statements:
System.out.println("Current BMI:");
System.out.println(bmi);
Notice that we can include a variable in a println statement the same way that
we include literal values and other expressions to be printed.
As its name implies, a variable can take on different values at different times. For
example, consider the following variation of the BMI program, which computes a new
BMI assuming the person lost 15 pounds (going from 195 pounds to 180 pounds).
1 public class BMICalculator2 {
2 public static void main(String[] args) {
3 // declare variables
4 double height;
5 double weight;
6 double bmi;
7
8 // compute BMI
9 height = 70;
10 weight = 195;
11 bmi = weight / (height * height) * 703;
12
13 // print results
14 System.out.println("Previous BMI:");
15 System.out.println(bmi);
16
17 // recompute BMI
18 weight = 180;
19 bmi = weight / (height * height) * 703;
20
21 // report new results
22 System.out.println("Current BMI:");
23 System.out.println(bmi);
24 }
25 }
 
Search WWH ::




Custom Search