为什么我在没有 'if' 的情况下收到 'else' 的编译时错误。谁能详细解释一下

Why I am getting compile time error as 'else' without 'if'. Can anyone explain me with detail

为什么我在 'else' 没有 'if' 的情况下出现编译时错误。谁能详细解释一下

class Test
    {
        public static void main(String[] args)
        {
            if(false)
                if(true)
                    if(false)
                    else
                        System.out.println("1");
                else
                    System.out.println("2");
            else
                System.out.println("3");
        }
    }

最里面的 if(false) 缺少一个语句。除非你想使用大括号,否则你必须在 if:

之后添加一个空操作语句
if(false);
else
    System.out.println("1");

或者您可以反转整个 if 链:

if(true)
    System.out.println("3");
else if(false)
    System.out.println("2");
else if(true)
    System.out.println("1");

这里使用了 2 个概念: 1. 如果 If 语句不使用大括号,则编译器只会将 If 语句的下一行视为完整的 If 块。 2.不能单独使用else语句。简单来说,else 语句只有在有 If 块时才能使用。

对于最里面的 If 语句,因为您在这里没有使用大括号,所以 'else' 是唯一要执行的语句。而且不能单独使用else语句。