这是我代码中的一个方法,当我尝试编译它时,它向我抛出一个“无法访问的语句”错误。
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;
^
然后我尝试使用我在以下代码中返回的这个 boolean 值:
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
我不确定上面的代码是否与问题相关,但我只是想展示我正尝试对抛出错误的 boolean 值执行的操作。谢谢。
最佳答案
return playerwhat;
永远无法到达,因为 if
或 else
子句将返回 true
或错误
。因此,您应该删除此声明。 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 {
...
}
关于java - 编译器给我一个 'unreachable statment' 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34015009/