我是新手编码,我有这个问题的任何帮助是感激的问题。
这是问题所在。
给定一个人的身高(英寸)和体重(磅),计算出他们的BMI。BMI计算为BMI =(体重*703)/(身高*身高)然后,根据他们的BMI,如果它小于18.5,则返回一条消息,说“你体重不足”。如果至少为26,则返回一条消息“您的体重是健康的”。如果是26或更多,则返回一条消息,提示“您超重了”。
BMIResult(177,69)→“你超重了。”
BMIResult(125,62)→“你的体重是健康的。”
BMIResult(95,64)→“你体重不足。”
提示:将BMI计算四舍五入到小数点后一位。确保返回的消息与显示的完全相同。
我做错了什么!!这就是我得到的错误。
错误:公有字符串BMIResult(双倍重,双高){
^^此方法必须返回String类型的结果
可能存在的问题:从理论上讲,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.";
}即使我试图从一个双精度数转换成一个字符串,它也不起作用。
发布于 2014-02-15 04:13:11
您应该尝试使用else,编译器不知道您的当前条件之一必须计算为true (因为如posted所示,它们都是独立且未连接的语句)。
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
}
}发布于 2014-02-15 04:15:35
下面是一个工作版本:
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的名称,如果没有执行任何if,则缺少返回语句。事实上,这种情况(很大程度上)是不可能发生的,只是编译器还不够聪明,不会知道这一点。
此外,不需要执行您正在进行的许多检查,因为如果前一条if语句失败,它们在逻辑上必须自动为真。类似地,不需要最后一个if,因为如果执行到了这一点,那么这个人显然超重了。
在Java中有命名约定,比如方法总是以小写字符开头。我已经将您的BMIResult()方法重命名为calculateBMI()。尽管如此,许多人还是会鼓励您编写calculateBmi(),因为这更符合现代风格。
发布于 2014-02-15 04:15:55
问题是,如果这两个条件都不满足,则不会返回任何内容。
使用:
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.
}https://stackoverflow.com/questions/21788661
复制相似问题