如何在Java中避免“无法访问的语句”和“else if if”?

问题描述:

所以我的代码是用来比较机器人的y坐标和目标的y坐标。我在添加打印语句时让函数返回任何东西时遇到问题。我有一种感觉,这与括号有关,但我不确定如何使用它们。如何在Java中避免“无法访问的语句”和“else if if”?

这不是整个程序,但它是唯一一个有错误的位。

当我尝试编译此:

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"); 

    } 
} 

我得到错误: '别人' 不“,如果'

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

+0

除了一个明显的问题,名为'isTargetNorth'的方法应该返回一个类型为'boolean'的值,而不是'byte'。 –

+1

信息的哪部分你不明白? – SLaks

+0

@RohitJain:虽然这里最糟糕的事情真的很远,不是吗? –

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

+0

我不知道,谢谢。 –

第一个:将它们各自的System.out.println调用后的返回语句移回 - 返回退出当前方法,因此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! 

的else没有如果的例子就是为什么你应该多加小心一个很好的提醒省略括号时。

在您的第一个代码块中,您在返回语句后使System.out.println无法访问。如果你把System.out.println放在return语句的前面,它就可以工作。

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

您写道:

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. 写括号{}莫尔写,但你总是可以看到块。