[英]Compiler giving me an 'unreachable statment' error
這是我的代碼中的一種方法,當我嘗試編譯它時,拋出“無法到達的語句”錯誤。
public static boolean whoareyou(String player)
{
boolean playerwhat;
if (player.equalsIgnoreCase("Player 1"))
{
return true;
}
else
{
return false;
}
return playerwhat;
}
確切的錯誤是:
java:82: error: unreachable statement
return playerwhat;
^
然后,我嘗試使用以下返回的布爾值:
public static int questions(int diceroll, int[] scorep1)
{
String wanttocont = " ";
boolean playerwhat;
for (int i = 0; i <= 6; i++)
{
while (!wanttocont.equalsIgnoreCase("No"))
{
wanttocont = input("Do you wish to continue?");
// boolean playerwhat; wasn't sure to declare here or outside loop
if (diceroll == 1)
{
String textinput = input("What's 9+10?");
int ans1 = Integer.parseInt(textinput);
output("That's certainly an interesting answer.");
if (ans1 == 19)
{
if (playerwhat = true)
{
output("Fantastic answer player 1, that's correct!");
diceroll = dicethrow(diceroll);
scorep1[0] = scorep1[0] + diceroll;
output("Move forward " + diceroll + " squares. You are on square " + scorep1[0]);
}
else if (playerwhat = false)
{
output("Fantastic answer player 2, that's correct!");
diceroll = dicethrow(diceroll);
scorep1[1] = scorep1[1] + diceroll;
output("Move forward " + diceroll + " squares. You are on square " + scorep1[1]);
}
} // END if diceroll is 1
} // END while wanttocont
} // END for loop
} // END questions
我不確定上面的代碼是否與問題有關,但我只是想說明我要如何處理拋出錯誤的布爾值。 謝謝。
return playerwhat;
永遠無法達到,因為if
或else
子句將返回true
或false
。 因此,您應該刪除此語句。 playerwhat
變量。
順便說一句,您的方法可以用一種內襯方法代替:
public static boolean whoareyou(String player)
{
return player.equalsIgnoreCase("Player 1");
}
我將此方法重命名為更具描述性的名稱,例如isFirstPlayer
。
編輯:
您永遠不會稱呼whoareyou
為您的questions
方法。 您應該稱呼它為:
更換
if (playerwhat = true) // this is assigning true to that variable, not comparing it to true
同
if (whoareyou(whateverStringContainsTheCurrentPlayer)) {
..
} else {
...
}
只是這樣更新代碼
public static boolean whoareyou(String player)
{
boolean playerwhat;
if (player.equalsIgnoreCase("Player 1"))
{
playerwhat = true;
}
else
{
playerwhat = false;
}
return playerwhat;
}
嘗試這個:
public static boolean whoareyou(String player)
{
return player.equalsIgnoreCase("Player 1");
}
您遇到了問題,因為:
return player what;
永遠不會到達。 您可以通過“ if”部分或“ else”部分退出函數。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.