Body mass index

The problem

Write a program that calculates and displays a person's body mass index (BMI). A person's BMI is calculated with the following formula: BMI = weight x 703 / height ^ 2. Where weight is measured in pounds and height is measured in inches. Display a message indicating whether the person has optimal weight, is underweight, or is overweight. A sedentary person's weight is considered optimal if his or her BMI is between 18.5 and 25. If the BMI is less than 18.5, the person is considered underweight. If the BMI value is greater than 25, the person is considered overweight.

Breaking it down

create variables

// Variables
double weight; // The user's weight
double height; // The user's height
double bmi; // The user's BMI

Ask the user for input

// Create a Scanner object for keyboard input.
Scanner keyboard = new Scanner(System.in);
 
// Tell the user what the program will do.
System.out.println("This program will calculate your body mass index, or BMI.");
 
// Get the user's weight.
System.out.print("Enter your weight, in pounds: ");
weight = keyboard.nextDouble();
 
// Get the user's height.
System.out.print("Enter your height, in inches: ");
height = keyboard.nextDouble();

Calculate bmi

static double calculateBMI (double height, double weight) {
    return weight * 703 / (height * height);
}

Determine description

static String bmiDescription (double bmi) {
    if (bmi < 18.5) {
        return "You are underweight.";
    } else {
        if (bmi > 25) {
            return "You are overweight.";
        } else {
            return "Your weight is optimal.";
        }
    }
}

Display output

// Calculate the user's body mass index.
bmi =  calculateBMI(height, weight);
 
// Display the user's BMI.
System.out.println("Your body mass index (BMI) is " + bmi);
 
System.out.println(bmiDescription(bmi));

Output

This program will calculate your body mass index, or BMI.
Enter your weight, in pounds: 220
Enter your height, in inches: 68
Your body mass index (BMI) is 33.44723183391003
You are overweight.

Unit tests

@Test
public void calculate_bmi () {
    assertTrue(BodyMassIndex.calculateBMI(73, 250) == 32.9799211859636);
}

@Test
public void bmiDescription_underweight () {
    assertEquals("You are underweight.", BodyMassIndex.bmiDescription(16));
}

@Test
public void bmiDescription_overweight () {
    assertEquals("You are overweight.", BodyMassIndex.bmiDescription(78));
}

@Test
public void bmiDescription_optimal () {
    assertEquals("Your weight is optimal.", BodyMassIndex.bmiDescription(20));
}

Level Up

  • Add validation to verify input
  • In the calculate BMI method add conditional for division by 0
  • Most people know their height in feet such as 5'9", provide the option to enter in feet