java - 编译器给我一个 'unreachable statment' 错误

标签 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;
                ^

然后我尝试使用我在以下代码中返回的这个 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; 永远无法到达,因为 ifelse 子句将返回 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/

相关文章:

java - 如何在 hibernate 验证之前开始 Flyway 迁移?

java - 挥杆:对齐问题

swift - EXC_BAD_INSTRUCTION(代码 = EXC_I386_INVOP,子代码 = 0x0)

Angular 5 无法使用 GreenSock 动画文件

java - 包与 Java 9 中的自动模块冲突

java - Spring Boot Controller 端点未启用?

java - 运行 javafx 程序时出现 InvocationTargetException

java - 我必须打印出这个方程的 5 个 future 值

html - 页脚代码在CSS样式表中显示为红色,但是HTML代码很好

Android 出现 eclipse proguard.cfg 问题