[英]Complex Conditionals and Unreachable Statements
我对Java非常陌生,遇到了一些麻烦。 我觉得这很容易解决。 基本上,我希望在满足两个条件的情况下返回声明。 下面是我的附加代码。
boolean Windy = false;
if (Windy = true)
return "It is Windy";
else
return "Not Windy";
if (temperature < 30);
{return "Too Windy or Cold! Enjoy watching the weather through the window";
我尝试更改脚本后,抛出其他错误,声称需要返回语句。
您的代码包含几个错误:
=
在Windy = true
应该是一个==
代替。 =
是分配东西,而==
是检查是否相等。 if (Windy = true) return "It is Windy"; else return "Not Windy";
if (Windy = true) return "It is Windy"; else return "Not Windy";
将始终返回两者之一,因此您下面的其余代码将无法访问,并且将永远不会执行。 if (temperature < 30);
应该删除。 {}
-block是不必要的。 我认为这是您在代码中寻找的东西:
boolean windy = false;
if(windy){
return "It is Windy";
} else if(temperature < 30){
return "Too Windy or Cold! Enjoy watching the weather through the window";
} else{
return "Not Windy";
}
当然,将windy
设置为false
硬编码的kinda也会使第一次检查也无法实现。 但是我认为这只是您的示例代码,在您的实际代码中,您将windy
检索为类变量或方法参数。
另外,由于windy
本身是一个布尔值,因此== true
是多余的,而if(windy)
就足够了。
PS:Java中的变量名称最好是camelCase,因此在这种情况下,请使用windy
而不是Windy
。
我还在if / else-if / else语句周围添加了括号。 它们不是必需的,如果您确实愿意,可以将其排除在外,但是修改代码更容易,以后不会出错。
好的,我检查了您的图像(通常不执行此操作),并在您的代码中发现了几个问题。
public static String getWeatherAdvice(int temperature, String description)
{
{ // REMOVE THIS BRACKET
if ( Windy = true) // = signifies an assigning a value, not a comparison. Use ==
return "It is Windy";
else
return "Not Windy";
if ( temperature < 30 ); // Since the above if-else will always return a value, this
// code can not be reached. Put this if before the previous if-else. Also: remove the ; after the if statement, otherwise, it ends the if, and the return statement might be triggered.
{ // don't put this bracket if you have a ; after the if
return "Too windy ... ";
} // don't put this bracket if you have a ; after the if
} // REMOVE THIS BRACKET
}
您的代码的更正版本(可能是):
public static String getWeatherAdvice(int temperature, String description)
{
if ( temperature < 30 )
{
return "Too windy ... ";
}
if ( Windy == true) // can also be written as: if ( Windy )
return "It is Windy";
else
return "Not Windy";
}
您可以使用“ &&” =和“ ||”比较条件 =或:
if (Windy && temperature < 30) {
return "it's windy and temperature is <30";
} else if (!Windy && temperature > 30) {
return "Not Windy";
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.