Now that we know how to get input from the user and store it into variables
and since we know how to do some basic math, we can now write our first
*useful* program!

1 import java.util.Scanner; 2 3 public class BMICalculator 4 { 5 public static void main( String[] args ) 6 { 7 Scanner keyboard = new Scanner(System.in); 8 double m, kg, bmi; 9 10 System.out.print( "Your height in m: " ); 11 m = keyboard.nextDouble(); 12 13 System.out.print( "Your weight in kg: " ); 14 kg = keyboard.nextDouble(); 15 16 bmi = kg / (m*m); 17 18 System.out.println( "Your BMI is " + bmi ); 19 } 20 }

Your height in m: 1.75 Your weight in kg: 73 Your BMI is 23.836734693877553

This exercise is (hopefully) pretty straightforward. We have three variables
(all doubles): *m* (meters), *kg* (kilograms) and *bmi* (body mass index).
We read in values for *m* and *kg*, but *bmi*’s value comes not from the
human but as the result of a calculation. On line 16 we compute the mass
divided by the square of the height and store the result into *bmi*.
And then we print it out.

The body mass index (BMI) is commonly used by health and nutrition professionals to estimate human body fat in populations. So this result would be informative for a health professional. For now that’s all we can do with it.

Eventually we will learn how to display a different message on the screen
*depending* on what the BMI equals, but for now this will have to do.

A pretty easy assignment for today, but I have some challenges for you in the Study Drills that should make things a bit tougher.

- Add some variables and change the program so that the human can input their weight and height using pounds and inches, and then convert those values to kilograms and meters to figure the BMI.

Your height in inches: 69 Your weight in pounds: 160 Your BMI is 23.625289

- Make it so the human can input their height in feet and inches separately.

Your height (feet only): 5 Your height (inches): 9 Your weight in pounds: 160 Your BMI is 23.625289

“Learn Java the Hard Way” is ©2013 Graham Mitchell