BMI计算器无法打印结果

时间:2016-10-26 18:28:46

标签: java

作为我的CS研究的一部分,我们开始学习java,我想做一个小小的项目,试图在Java上比我更好。

到目前为止它没有按预期工作。

我写了这段代码:

import java.util.Scanner;

public class BodyWeightCalculator {

public static void main(String[] args) {
    double weight;
    double height;

    Scanner input = new Scanner(System.in);

    System.out.print("What's your height in meters?");
    height = input.nextDouble();
    System.out.print("What's your weight in kilograms?");
    weight = input.nextDouble();

    double bmi = ((weight / height) / height);

    System.out.printf("Your BMI is " + bmi);

    if (bmi < 18.5)
        System.out.println("Your BMI is " + bmi + ", you are underweight.");
    else if (bmi <= 18.5 & bmi > 24.9)
        System.out.println("Your BMI is " + bmi + ", you are at a normal weight.");
    else if (bmi < 25 & bmi > 29.9)
        System.out.println("Your BMI is " + bmi + ", you are overweight");
    else if (bmi > 30) {
        System.out.println("Your BMI is " + bmi + ", you are extremely overweight");
    }
}
}

此程序要求用户输入他/她的体重和身高,然后输出用户的BMI以及他/她是否正常体重或体重不足等。

程序仅输出BMI,忽略所有if-else语句。

这有什么不对吗?

2 个答案:

答案 0 :(得分:1)

您在if-else语句集中存在问题,它应涵盖整个范围。您应该使用boolean运营商&#39;&amp;&amp;&#39;而不是使用bitwise-operator&#39;&amp;&#39;。

 if (bmi < 18.5)
    System.out.println("Your BMI is " + bmi + ", you are underweight.");
else if (bmi >= 18.5 && bmi <= 24.9)
    System.out.println("Your BMI is " + bmi + ", you are at a normal weight.");
else if (bmi >= 25 && bmi <= 29.9)
    System.out.println("Your BMI is " + bmi + ", you are overweight");
else if (bmi >= 30.) {
    System.out.println("Your BMI is " + bmi + ", you are extremely overweight"); 
}

答案 1 :(得分:0)

您的if语句似乎不包括您想要的范围。此外,您应该使用&#34;&amp;&amp;&#34;为&#34;和&#34;而不是&#34;&amp;&#34;,这是一个有点明智的&#34;和&#34;。您还应该养成为if语句块使用大括号的习惯,即使该块是一行。

你应该像这样重写你的陈述:

    if (bmi < 18.5) {
        System.out.println("Your BMI is " + bmi + ", you are underweight.");
    }
    else if (18.5 <= bmi && bmi < 25.0) {
        System.out.println("Your BMI is " + bmi + ", you are at a normal weight.");
    }
    else if (25.0 <= bmi && bmi < 30.0) {
        System.out.println("Your BMI is " + bmi + ", you are overweight");
    }
    else if (30.0 <= bmi) {
        System.out.println("Your BMI is " + bmi + ", you are extremely overweight");
    }
    else {
        throw new RuntimeException("Should not be reached. BMI=" + bmi);
    }