这是我的代码中的一个方法,当我试图编译它时,它会抛出一个“无法到达的语句”错误。
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我不确定上面的代码是否与这个问题相关,但我只想展示一下我试图用布尔值做什么,这个布尔值会给我带来错误。谢谢。
发布于 2015-12-01 07:40:37
永远无法到达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 {
...
}发布于 2015-12-01 07:42:49
只需这样更新代码即可。
public static boolean whoareyou(String player)
{
boolean playerwhat;
if (player.equalsIgnoreCase("Player 1"))
{
playerwhat = true;
}
else
{
playerwhat = false;
}
return playerwhat;
}发布于 2015-12-01 07:43:45
试试这个:
public static boolean whoareyou(String player)
{
return player.equalsIgnoreCase("Player 1");
}你有问题,因为:
还球员什么;
永远达不到。您可以通过“if”或“either”-part退出函数。
https://stackoverflow.com/questions/34015009
复制相似问题