【问题标题】:How to avoid "unreachable statement" and "else without if" in Java?如何避免 Java 中的“unreachable statement”和“else without if”?
【发布时间】:2013-10-27 20:37:56
【问题描述】:

所以我的代码旨在将机器人的 y 坐标与目标的 y 坐标进行比较。当我添加打印语句时,我无法让函数返回任何内容。我感觉这与括号有关,但我不确定如何使用它们。

这不是整个程序,但它是其中唯一有错误的部分。

当我尝试编译时:

public class Ex12 
{

    private byte isTargetNorth(IRobot robot)
    {

        if (robot.getLocationY() > robot.getTargetLocation().y) {

            return 1; System.out.println("north");

        } else if (robot.getLocationY() == robot.getTargetLocation().y) {

            return 0; System.out.println("no");

        } else { 

            return -1; System.out.println("south");

        }  

    }
}

我收到错误:无法访问的语句

当我尝试这个时:

public class Ex12 
{

    private byte isTargetNorth(IRobot robot)
    {

        if (robot.getLocationY() > robot.getTargetLocation().y)

            return 1; System.out.println("north");

        else if (robot.getLocationY() == robot.getTargetLocation().y)

            return 0; System.out.println("no");

        else

            return -1; System.out.println("south");

    }
}

我得到错误:没有'if'的'else'

当我删除 System.out.println() 函数时,我没有收到任何错误。

【问题讨论】:

  • 除了明显的问题之外,名称为isTargetNorth 的方法实际上应该返回boolean 类型的值,而不是byte
  • 邮件的哪一部分你不明白?
  • @RohitJain:这还不是最糟糕的错误,不是吗?
  • 返回前打印消息,返回后不能做某事(不使用try/finally)
  • @JonSkeet 是的。真正的问题已经得到解答。 :)

标签: java if-statement unreachable-statement


【解决方案1】:

return 语句退出您的方法。所以,System.out 永远不会被调用。

【讨论】:

    【解决方案2】:

    第一个:在各自的 System.out.println 调用之后移动 return 语句 - return 退出当前方法,因此 System.out.println 永远不会被调用,因此无法访问。

    第二个是格式混乱的情况:你的代码

    if (robot.getLocationY() > robot.getTargetLocation().y)
        return 1; System.out.println("north");
    else if ...
    //...
    

    其实等价于

    if (robot.getLocationY() > robot.getTargetLocation().y) {
        return 1;
    }
    System.out.println("north");
    else if ... //else without if right here, because else should follow immediately after an if block!
    

    没有 if 的 else 示例很好地提醒了您为什么在省略大括号时应该格外小心。

    【讨论】:

      【解决方案3】:

      在您的第一个代码块中,您在 return 语句之后有 System.out.println,这使得它们无法访问。如果将 System.out.println 放在 return 语句的前面,它会起作用。

      在您的第二个示例中,您从 if 语句中删除了方块 ({...}),这意味着每个条件只能有一个语句。你有两个 return 和 System.out.println。

      【讨论】:

        【解决方案4】:

        你写道:

        return 1;
        System.out.println(""); // << This is written after you return to the calling method.
        

        这意味着,你不能在这里写代码。

        在您编写的其他代码中

        if() Some Code;
        // This statement will be executed, because  it is outside of the if-block
        else 
            // The else above has no if.
        

        解决您的问题:

        1. 返回返回值后切勿编写代码。
        2. 写括号{}Mor 写,但总能看到块。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2012-04-27
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多