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
为真!
结果是 else
与最近的绑定,如果
,虽然我没有在任何地方找到它,并且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
/的绑定顺序在哪里?
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
是内部<$ c $的一部分c> 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屋!