Java if-if-else 行为 [英] Java if-if-else behavior
问题描述
我在我的代码中编写了一个简单的 if/else
,效果很好.后来我在第一个下面添加了另一个级别的 if
,并被它的行为所困惑.这是重现这种情况的非常简单的代码:
I wrote a simple if/else
in my code which worked fine. Later I added another level of if
under the first, and was baffled by its behavior. Here's very simple code to recreate the situation:
public static void main(String[] args) {
boolean a = true;
boolean b = false;
if (a)
if (b)
System.out.println("a=true, b=true");
else
System.out.println("a=false");
}
它返回a=false
",即使a
为真!
It returns "a=false
", even though a
is true!
事实证明 else
与最近的 if
绑定,虽然我没有发现它在任何地方记录,而且 eclipse 没有将不匹配的缩进级别突出显示为错误(虽然它在格式化文件时确实纠正了它).
It turns out the else
binds with the nearest if
, although I have not found it documented anywhere, and eclipse does not highlight the mismatched indentation levels as an error (although it does correct it when formatting the file).
使用大括号的一个非常非常有力的论据!
A very, very strong argument for using braces!
else
/if
的绑定顺序在哪里记录?
Where is the binding order of
else
/if
documented?
作为一个挑战,
有没有办法让上面的代码在不添加大括号的情况下做你期望的缩进?
Is there a way to make the above code do what the indentation makes you expect without adding braces?
推荐答案
有没有办法让上面的代码在不添加大括号的情况下做你期望的缩进?
Is there a way to make the above code do what the indentation makes you expect without adding braces?
没有.因为 Java 不是 Python,编译器不会根据您的想法工作.这就是为什么你应该总是使用大括号.
No. Because Java is not Python, and compiler doesn't work based on what's on your mind. That is why you should always use braces.
显然 else
是内部 if
的一部分,因此结果是预期的.这在 JLS §14.5 - 声明中很明显
Clearly the else
is a part of the inner if
, and hence the result is expected. This is evident from JLS §14.5 - Statements
这篇关于Java if-if-else 行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!