Learn Java the Hard Way (Second Edition)

Exercise 9: Calculations with User Input

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     public static void main( String[] args ) {
 5         Scanner keyboard = new Scanner(System.in);
 6         double m, kg, bmi;
 7 
 8         System.out.print( "Your height in m: " );
 9         m = keyboard.nextDouble();
10 
11         System.out.print( "Your weight in kg: " );
12         kg = keyboard.nextDouble();
13 
14         bmi = kg / (m*m);
15 
16         System.out.println( "Your BMI is " + bmi );
17     }
18 }

What You Should See

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 14 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 value is in the BMI variable, but for now this will have to do.

Today’s exercise is hopefully pretty easy to understand, but the Study Drills are quite a bit tougher than usual this time. If you can get them done without help, then your understanding is probably pretty good.


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