2014-02-14 112 views
1

我是新来的编码和我有这个问题的任何帮助表示赞赏。编码蝙蝠运动BMIResult

这是问题所在。

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

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

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

BMIResult(95,64)→“你体重不足。”提示:将您的BMI计算舍入到小数点后一位。确保消息返回完全如显示。

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

错误:公共字符串BMIResult(双重,双倍高度){

^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ ^^^^^^^^^ 此方法必须返回字符串类型的结果

可能的问题:if语句结构理论上可能允许运行在不调用return的情况下到达方法的结尾。 考虑在方法中添加最后一行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."; 



} 

即使我尝试从一个双重转换为字符串这是行不通的。

+1

你不处理BMI = = 18.5的情况下,BTW。 –

回答

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 
    } 
} 
+0

谢谢你工作! – sciontoygirl

0

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

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)); 
    } 
} 

与原代码的问题是,如果没有IFS的执行变量bmi的名称和缺少return语句。事实上,这种情况(几乎)不可能发生,但编译器不够聪明。

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

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

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. 


}