[英]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.