HOWTO · Java

用 Java 制作一个 BMI 计算器

本教程演示如何在 Java 中创建 BMI 计算器。

本页内容

BMI 代表体重指数。本教程演示了如何在 Java 中创建 BMI 计算器。

用 Java 制作一个 BMI 计算器

体重指数 BMI 是基于身高和体重的健康指标。BMI 的计算方法是将体重(公斤)除以身高(米)的平方。

计算 BMI 的公式是:

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

BMI 的范围如下表所示:

BMI 范围 类别
> 30 肥胖
25 - 30 超重
18.5 - 25 正常
< 18.5 体重不足

让我们用 Java 实现 BMI 指数计算器:

package delftstack;

import java.util.Scanner;

public class Calculate_BMI {
  // method to check BMI
  public static String BMIChecker(double Weight, double Height) {
    // calculate the BMI
    double BMI = Weight / (Height * Height);

    // check the range of BMI
    if (BMI < 18.5)
      return "Underweight";
    else if (BMI < 25)
      return "Normal";
    else if (BMI < 30)
      return "Overweight";
    else
      return "Obese";
  }

  public static void main(String[] args) {
    double Weight = 0.0f;
    double Height = 0.0f;
    String BMI_Result = null;

    Scanner scan_input = new Scanner(System.in);
    System.out.print("Please enter the weight in Kgs: ");
    Weight = scan_input.nextDouble();
    System.out.print("Pleae enter the height in meters: ");
    Height = scan_input.nextDouble();

    BMI_Result = BMIChecker(Weight, Height);

    System.out.println(BMI_Result);

    scan_input.close();
  }
}

上面的代码将输入体重和身高,然后检查 BMI 的类别。见输出:

Please enter the weight in Kgs: 79
Please enter the height in meters: 1.86
Normal