Ever wondered how apps calculate your Body Mass Index (BMI)? Let’s build one in Java!
This project is simple but teaches you important programming skills:
Taking user input
Doing calculations
Using conditions (if-else)
Printing results
📝 1. What is BMI?
BMI = weight (kg) ÷ height² (m²)
It’s a simple formula doctors use to check if your weight is in a healthy range.
Categories:
BMI < 18.5 → Underweight
18.5 ≤ BMI < 24.9 → Normal weight
25 ≤ BMI < 29.9 → Overweight
BMI ≥ 30 → Obese
💻 2. The Java Program
Here’s the full code:
import java.util.Scanner;
public class BMICalculator {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
// Get weight
System.out.print("Enter your weight in kilograms: ");
double weightInKg = scanner.nextDouble();
// Get height
System.out.print("Enter your height in meters: ");
double heightInMeters = scanner.nextDouble();
// Calculate BMI
double bmi = weightInKg / (heightInMeters * heightInMeters);
bmi = Math.round(bmi * 100.0) / 100.0; // round to 2 decimal places
// Determine category
String bmiCategory;
if (bmi < 18.5) {
bmiCategory = "Underweight";
} else if (bmi >= 18.5 && bmi < 24.9) {
bmiCategory = "Normal weight";
} else if (bmi >= 25 && bmi < 29.9) {
bmiCategory = "Overweight";
} else {
bmiCategory = "Obese";
}
// Print result
System.out.println("\nYour BMI is: " + bmi);
System.out.println("BMI Category: " + bmiCategory);
scanner.close();
}
}
🔍 3. Key Parts Explained
✅ User Input with Scanner
We use Scanner to ask the user for weight and height.
Scanner scanner = new Scanner(System.in);
double weightInKg = scanner.nextDouble();
👉 Takeaway: This is how Java reads numbers typed by the user.
✅ BMI Calculation
The formula is applied directly:
double bmi = weightInKg / (heightInMeters * heightInMeters);
We then round it:
bmi = Math.round(bmi * 100.0) / 100.0;
👉 Takeaway: Multiplying by 100 and dividing back is a common trick to round to 2 decimals.
✅ Using if-else for Categories
if (bmi < 18.5) {
bmiCategory = "Underweight";
} else if (bmi >= 18.5 && bmi < 24.9) {
bmiCategory = "Normal weight";
}
// ...
👉 Takeaway: Conditions allow your program to make decisions.
🚀 4. Try It Out
Example Run:
Enter your weight in kilograms: 68
Enter your height in meters: 1.75
Your BMI is: 22.2
BMI Category: Normal weight
💡 5. Possible Improvements
If you want to expand this project:
Validate input (what if the user types text instead of numbers?).
Convert units (accept pounds and inches).
Add health tips based on BMI result.
Build a GUI version with JavaFX or Swing.
🎯 Final Thoughts
This project shows how you can take a real-world formula and turn it into working code.
You practiced:
✔ Reading user input
✔ Doing math in Java
✔ Making decisions with if-else
✔ Formatting output
💬 Question for you:
👉 What would you add next — unit conversion, GUI, or health tips?
Top comments (0)