gpt4 book ai didi

Java语句,处理优先级("dangling else")

转载 作者:塔克拉玛干 更新时间:2023-11-03 03:50:00 28 4
gpt4 key购买 nike

给定以下有效代码:

Boolean a = false;

if (a)
System.out.println("A");
else
System.out.println("!A");

根据documentation , if 包括它的条件和内部的 statement 也是一个 statement。例如:

   if (b){
System.out.println("B");
}

是一个语句

但是,当我们要用另一个语句替换现有语句时,它不应该触及整体逻辑,对吧?假设我们将 (Expression)-statement 替换为上面的 if-statement :

Boolean a = false;
Boolean b = false:

if (a)
if (b){
System.out.println("A and B");
}
else
System.out.println("!A");

Java Compiler 将解释代码示例如下(完整的括号解释):

Boolean a = false;
Boolean b = false:

if (a){
if (b){
System.out.println("A and B");
} else {
System.out.println("!A");
}
}

这不是最初的逻辑。

那么为什么将一个语句与另一个语句交换会改变逻辑?

从示例中可以清楚地看出,问题出在 大括号 上,但如果省略大括号,我找不到有关 java 准确处理此问题的方式的信息。

是否有关于此行为的任何记录?为什么 java 更喜欢将 else 连接到最近的 if,而不是它在解析时遇到的第一个 if

最佳答案

当然,答案在Java Language Specification中.相关部分是section 14.5, "Statements" ,它恰好描述了这种情况:

As in C and C++, the if statement of the Java programming language suffers from the so-called "dangling else problem," illustrated by this misleadingly formatted example:

if (door.isOpen())
if (resident.isVisible())
resident.greet("Hello!");
else door.bell.ring(); // A "dangling else"

The problem is that both the outer if statement and the inner if statement might conceivably own the else clause. In this example, one might surmise that the programmer intended the else clause to belong to the outer if statement.

最后:

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语句,处理优先级("dangling else"),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32076762/

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