我在我的代码中写了一个简单的 if/else
,效果很好。后来我在第一层下添加了另一层 if
,并且对其行为感到困惑。这是重现这种情况的非常简单的代码:
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
与最近的 if
绑定(bind),尽管我没有在任何地方找到它的文档,并且 eclipse 不会将不匹配的缩进级别突出显示为错误(尽管它在格式化文件时确实会更正它)。
使用大括号的一个非常非常有力的论据!
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,并且编译器不会根据您的想法工作。这就是为什么您应该始终使用大括号。
显然 else
是内部 if
的一部分,因此结果是预期的。从 JLS §14.5 - Statements 可以看出这一点
关于Java if-if-else 行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23140263/