How to Write a BMI Calculator in Java

BMI stands for Body Mass Index. It is a measure of body mass based on height and weight of an individual. Using the range of BMI, individuals are classified as underweight, normal or overweight. Its value is in a specific range for a healthy individual. The following table shows the main BMI categories.

Category BMI Range
Underweight < 18.5
Normal 18.5 – 25
Overweight 25 – 30
Obese > 30

Formula for Calculating BMI in Metric Units

BMI = Weight in Kg/(Height in Meters * Height in Meters)

Example calculation for weight = 90kg, height = 1.5m

BMI = 90/(1.5*1.5) = 40

The following example program in Java calculates BMI value based on inputs in metric units. Note that the program takes the height input in centimeters.

import java.util.Scanner;

// BMI Calculator in Java
// Uses metric units
public class BMICalculatorInMetric {

    public static void main(String[] args) throws Exception {
        calculateBMI();
    }

    private static void calculateBMI() throws Exception {
        System.out.print("Please enter your weight in kg: ");
        Scanner s = new Scanner(System.in);
        float weight = s.nextFloat();
        System.out.print("Please enter your height in cm: ");
        float height = s.nextFloat();
        
        // multiplication by 100*100 for cm to m conversion
        float bmi = (100*100*weight)/(height*height);
        
        System.out.println("Your BMI is: "+bmi);
        printBMICategory(bmi);
        
    }
    
    // Prints BMI category
    private static void printBMICategory(float bmi) {
        if(bmi < 18.5) {
            System.out.println("You are underweight");
        }else if (bmi < 25) {
            System.out.println("You are normal");
        }else if (bmi < 30) {
            System.out.println("You are overweight");
        }else {
            System.out.println("You are obese");
        }
    }
}

Do you have a programming problem that you are unable to solve? Please send us your problem and we will publish the solution! Please email us.

Leave a Reply