编译器给我一个'无法达到的声明'错误

时间:2015-12-01 07:39:25

标签: java compiler-errors

这是我的代码中的一个方法,当我尝试编译它时,它会给我一个“无法访问的语句”错误。

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

我不确定上面的代码是否与问题相关,但我只是想表明我试图用布尔值来解决这个问题。谢谢。

3 个答案:

答案 0 :(得分:2)

永远无法联系到{p> return playerwhat;,因为ifelse子句将返回truefalse。因此,您应该删除此声明。 <{1}}变量不是必需的。

顺便说一句,你的方法可以用单线法替换:

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

答案 1 :(得分:2)

只需以这种方式更新您的代码

public static boolean whoareyou(String player)
{
    boolean playerwhat;
    if (player.equalsIgnoreCase("Player 1"))
    {
        playerwhat = true;
    }
    else
    {
        playerwhat = false;
    }
    return playerwhat;
}

答案 2 :(得分:2)

试试这个:

return player what;

你有这个问题,因为:

adj[v].push_back(u);

永远不会到达。您可以通过“if” - 或通过“else”-part退出您的函数。