编码蝙蝠练习BMIResult

时间:2014-02-14 20:10:06

标签: java

我是编码的新手,我遇到了这个问题的任何问题。

这是问题所在。

考虑到个人身高(英寸)和体重(磅),计算他们的BMI。 BMI计算为BMI =(体重* 703)/(身高*身高)然后,根据他们的BMI,如果它小于18.5,则返回一条消息“你体重不足”。如果它至少不超过26,则返回一条消息“您的体重是健康的”。如果是26或更多,则返回一条消息“你超重。”

BMIResult(177,69)→“你超重。”

BMIResult(125,62)→“你的体重是健康的。”

BMIResult(95,64)→“你体重不足。”

提示:将BMI计算舍入到小数点后一位。确保消息返回完全一样。

我做错了什么!!这是我得到的错误。

错误:public String BMIResult(双倍体重,双倍高度){

^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 此方法必须返回String

类型的结果

可能的问题:理论上可能是if语句结构 允许运行到达方法的末尾而不调用return。 考虑在方法中添加最后一行返回some_value; 所以总会返回一个值。

这是我的错误消息上面的代码:

public String BMIResult(double weight,double height) {
double bmi=((weight*703)/(height*height));

if (BMI<18.5)

  return "You are underweight.";

if (BMI>18.5 && BMI<26)

  return "Your weight is healthy.";

if (BMI>=26)

  return "You are overweight.";



}

即使我尝试从双字符串转换为字符串,它也不起作用。

4 个答案:

答案 0 :(得分:1)

您应该尝试使用else,编译器不知道您当前的一个条件必须评估为true(因为发布时它们都是独立且未连接的语句)。

public String BMIResult(double weight,double height) {
  double bmi=((weight*703)/(height*height));
  if (BMI<18.5) {
    return "You are underweight.";
  } else if (BMI<26) { // BMI>=18.5 not needed, or the first if would be entered.
    return "Your weight is healthy.";
  } else { // <-- you might omit this else entirely, and end the method
    return "You are overweight."; // <-- with this
  }
}

答案 1 :(得分:1)

这是一个有效的版本:

public class BMI {

    public String calculateBMI(double weight, double height) {
        double bmi = ((weight * 703) / (height * height));

        if (bmi < 18.5) {
            return "You are underweight.";
        }
        if (bmi < 26) {
            return "Your weight is healthy.";
        }

        return "You are overweight.";
    }

    public static void main(String[] args) {
        System.out.println(new BMI().calculateBMI(95, 64));
    }
}

原始代码的问题是变量bmi的名称,如果没有执行任何ifs,则缺少return语句。事实上,这种情况(几乎)不可能发生,但编译器并不聪明,不知道。

此外,您无需执行许多检查,因为如果先前的if语句失败,它们在逻辑上必须自动为真。同样地,不需要最后一个if,因为如果执行到了这一点,那么这个人显然是超重的。

在Java中有命名约定,例如方法总是以小写字符开头。我已将您的BMIResult()方法重命名为calculateBMI()。虽然,很多人会鼓励你写calculateBmi(),因为它更符合现代风格。

答案 2 :(得分:1)

问题是,如果两个条件都不满足,则不会返回任何条件。

使用:

public String BMIResult(double weight,double height) {
double bmi=((weight*703)/(height*height));

if (BMI<18.5)

  return "You are underweight.";

if (BMI>18.5 && BMI<26)

  return "Your weight is healthy.";

if (BMI>=26)

  return "You are overweight.";

return ""; //add something.


}

答案 3 :(得分:0)

编译器不知道您的代码将执行您的一个if语句的代码。你必须在所有if的结尾处有一个返回,或者只是在结尾处写一个else。

相关问题