Create a BMI Calculator in Java – 在Java中创建一个BMI计算器

最后修改: 2022年 9月 21日

中文/混合/英文(键盘快捷键:t)

1. Overview

1.概述

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

在本教程中,我们将用Java创建一个BMI计算器。

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

在进入实施阶段之前,首先让我们了解一下BMI的概念。

2. What Is 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.

在BMI的帮助下,我们可以发现一个人的体重是否健康。

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

让我们看一下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范围,一个人被划分为体重不足、正常、超重或肥胖。

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).

例如,让我们计算一个体重为100公斤,身高为1.524米的人的BMI。

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”.

因为BMI大于30,所以被归类为 “超重”。

3. Java Program to Calculate BMI

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:

该Java程序由计算BMI的公式和简单的ifelse语句组成。使用该公式和上表,我们可以找出一个人所在的类别。

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. Testing

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. Conclusion

5.总结

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

在这篇文章中,我们学习了用Java创建一个BMI计算器。我们还通过写一个JUnit测试来测试该实现。

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

一如既往,该教程的完整代码可在GitHub上获取