if语句-嵌套的if - else在java中



我正在准备oca8考试…

在enthuware测试中有一个问题,下面的代码的正确结构是什么(比如哪个if属于哪个else——没有花括号)?

...
if
    statement 1;
if
    statement 2;
else
    statement 3;
else
    statement 4;
...

软件给出的答案是这样的…

if //statement 1
|  if //statement 2
|  |
|  else //statement 3
else //statement 4

但是当我在eclipse中执行代码时(没有花括号),我在最后的else中得到了编译时错误…

Exception in thread "main" java.lang.Error: Unresolved compilation problem: 
Syntax error on token "else", delete this token

那么,这是正确的/有效的/可能的吗?

如果不使用花括号,则只考虑if()之后的第一个语句。在您的情况下,两个if语句是嵌套的,但第一个else语句用于父if,因此第二个else没有if

不带大括号:

if (true)
         System.out.println("First if");
    else
        if (true)
            System.out.println("second if, first else");
        else
            System.out.println("second if, second else");
    System.out.println("outside statement");

尽管我强烈建议添加它们:

 if (true) {
        System.out.println("First if");
    } else if (true) {
        System.out.println("second if, first else");
    } else {
        System.out.println("second if, second else");
    }
    System.out.println("outside statement");

每个不带括号的if后面只有一条语句,所以:

if(value)
Sys.out.print("Cow");
Sys.out.print("Rabbit");

这里,如果value为真,则将打印"Cow"。但是,每次都会打印"Rabbit"。为了确保两个或更多的指令执行取决于if语句,你必须使用这样的块:

if(value){
 Sys.out.print("Cow");
 Sys.out.print("Rabbit");
}

所以当没有括号时,它不会编译为:

if
    statement 2;
else
    statement 3;

被视为1,并且只有一个其他语句被认为是if语句。第一个"if"只是一个独立的if语句,因此第二个else语句是错误的,因为它之前没有if语句。

最新更新