java 没有大括号的嵌套 if-else 行为

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17172536/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-01 01:12:02  来源:igfitidea点击:

Nested if-else behaviour without braces

javaif-statementsyntax

提问by usr-local-ΕΨΗΕΛΩΝ

Consider the following unformatted nested if-elseJava code

考虑以下未格式化的嵌套if-elseJava 代码

if (condition 1)
if (condition 2)
action 1;
else
action 2;

My question is: according to the Java language specifications, to what if does the elsebranch apply?

我的问题是:根据 Java 语言规范,如果else分支适用于什么?

By hand-reformatting and adding braces, which of these two is correct?

通过手动重新格式化和添加大括号,这两个中哪一个是正确的?

Block 1:

第 1 块:

if (condition 1) {
    if (condition 2) {
        action 1;
    } else
        action 2;
    }
}

Block 2:

第 2 块:

if (condition 1) {
    if (condition 2) {
        action 1;
    }
}
else {
    action 2;
}

回答by Vincent van der Weele

From the documentation:

文档

The Java programming language, like C and C++ and many programming languages before them, arbitrarily decrees that an else clause belongs to the innermost if to which it might possibly belong.

Java 编程语言与 C 和 C++ 以及它们之前的许多编程语言一样,任意规定 else 子句属于它可能所属的最内层 if。

回答by ThaBomb

Block 1 is correct, in if else situations with no brackets the else is linked to the nearest if

块 1 是正确的,在没有括号的 if else 情况下,else 链接到最近的 if

if (condition 1)  
if (condition 2)
action 1;
else
action 2;

is the same as

是相同的

if (condition 1)
    if (condition 2)
    action 1;
    else
    action 2;

also brackets are for the sake of understanding level, and ease. In larger if else statements, having no brackets makes error very common

括号也是为了理解层次,方便。在较大的 if else 语句中,没有括号会使错误非常普遍

回答by James Montagne

You can try it and find that the elseapplies to the inner if:

您可以尝试一下,发现else适用于内部if

http://ideone.com/iBorYi

http://ideone.com/iBorYi

This is a good reason not to write code like this. It's very hard to read and understand what is happening.

这是不编写这样的代码的一个很好的理由。很难阅读和理解正在发生的事情。

回答by Duracell De Monaco

Just my 2 cents for a better visual representation.

只需我的 2 美分即可获得更好的视觉表现。

Everything inside braces will be completely ignored.

大括号内的所有内容都将被完全忽略。

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