Java Reference
In-Depth Information
3.8 Case Study: Computing Body Mass Index
You can use nested if statements to write a program that interprets body mass index.
Key
Point
Body Mass Index (BMI) is a measure of health based on height and weight. It can be cal-
culated by taking your weight in kilograms and dividing it by the square of your height in
meters. The interpretation of BMI for people 20 years or older is as follows:
BMI
Interpretation
BMI < 18.5
Underweight
18.5 ≤ BMI < 25.0
Normal
25.0 ≤ BMI < 30.0
Overweight
30.0 ≤ BMI
Obese
Write a program that prompts the user to enter a weight in pounds and height in inches and
displays the BMI. Note that one pound is 0.45359237 kilograms and one inch is 0.0254
meters. Listing 3.4 gives the program.
L ISTING 3.4
ComputeAndInterpretBMI.java
1 import java.util.Scanner;
2
3 public class ComputeAndInterpretBMI {
4 public static void main(String[] args) {
5 Scanner input = new Scanner(System.in);
6
7 // Prompt the user to enter weight in pounds
8 System.out.print( "Enter weight in pounds: " );
9
double weight = input.nextDouble();
input weight
10
11 // Prompt the user to enter height in inches
12 System.out.print( "Enter height in inches: " );
13
double height = input.nextDouble();
input height
14
15
final double KILOGRAMS_PER_POUND = 0.45359237 ; // Constant
16
final double METERS_PER_INCH = 0.0254 ; // Constant
17
18 // Compute BMI
19 double weightInKilograms = weight * KILOGRAMS_PER_POUND;
20 double heightInMeters = height * METERS_PER_INCH;
21 double bmi = weightInKilograms /
22 (heightInMeters * heightInMeters);
23
24 // Display result
25 System.out.println( "BMI is " + bmi);
26 if (bmi < 18.5 )
27 System.out.println( "Underweight" );
28 else if (bmi < 25 )
29 System.out.println( "Normal" );
30 else if (bmi < 30 )
31 System.out.println( "Overweight" );
32 else
33 System.out.println( "Obese" );
34 }
35 }
compute bmi
display output
 
 
 
Search WWH ::




Custom Search