## 1.概述

In this tutorial, we’ll create a BMI Calculator in Java.

Before moving on to the implementation, first, let’s understand the concept of BMI.

## 2.什么是BMI？

BMI stands for Body Mass Index. It’s a value derived from an individual’s height and weight.

BMI是指身体质量指数。它是一个由个人的身高和体重得出的数值。

With the help of BMI, we can find out whether an individual’s weight is healthy or not.

Let’s have a look at the formula for calculating BMI:

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

BMI=体重（公斤）/（身高（米）*身高（米））

A person’s categorized as Underweight, Normal, Overweight, or Obese based on the BMI range:

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

For example, let’s calculate the BMI of an individual with a weight equal to 100kg (Kilograms) and a height equal to 1.524m (Meters).

BMI = 100 / (1.524 * 1.524)

BMI = 100 / (1.524 * 1.524)

BMI =  43.056

BMI=43.056

Since BMI is greater than 30, the person is categorized as “Overweight”.

## 3.计算BMI的Java程序

The Java program consists of the formula for calculating BMI and simple ifelse statements. Using the formula and the table above, we can find out the category an individual lies in:

``````static String calculateBMI(double weight, double height) {

double bmi = weight / (height * height);

if (bmi < 18.5) {
return "Underweight";
}
else if (bmi < 25) {
return "Normal";
}
else if (bmi < 30) {
return "Overweight";
}
else {
return "Obese";
}
}``````

## 4.测试

Let’s test the code by providing the height and weight of an individual who is “Obese”:

``````@Test
public void whenBMIIsGreaterThanThirty_thenObese() {
double weight = 50;
double height = 1.524;
String actual = BMICalculator.calculateBMI(weight, height);
String expected = "Obese";

assertThat(actual).isEqualTo(expected);
}``````

After running the test, we can see that the actual result is the same as the expected one.

## 5.总结

In this article, we learned to create a BMI Calculator in Java. We also tested the implementation by writing a JUnit test.

As always, the complete code for the tutorial is available over on GitHub.