gpt4 book ai didi

Java if-if-else 行为

转载 作者:搜寻专家 更新时间:2023-11-01 00:59:10 24 4
gpt4 key购买 nike

我在我的代码中写了一个简单的 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com