没有大括号的嵌套 if-else 行为 [英] Nested if-else behaviour without braces

查看:45
本文介绍了没有大括号的嵌套 if-else 行为的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑以下未格式化的嵌套if-else Java 代码

Consider the following unformatted nested if-else Java code

if (condition 1)
if (condition 2)
action 1;
else
action 2;

我的问题是:根据Java语言规范,如果else分支适用于什么情况?

My question is: according to the Java language specifications, to what if does the else branch apply?

通过手动重新格式化并添加大括号,这两个中哪一个是正确的?

By hand-reformatting and adding braces, which of these two is correct?

块 1:

if (condition 1) {
    if (condition 2) {
        action 1;
    } else
        action 2;
    }
}

块 2:

if (condition 1) {
    if (condition 2) {
        action 1;
    }
}
else {
    action 2;
}

推荐答案

来自 Java 语言规范:

Java 编程语言与 C 和 C++ 以及之前的许多编程语言一样,任意规定 else 子句属于它可能所属的最内层 if.

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.

这篇关于没有大括号的嵌套 if-else 行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆