为什么在Java中没有大括号的另一个IF内允许使用IF块 [英] Why an IF block is allowed inside another IF that doesn't have curly brackets in JAVA

查看:64
本文介绍了为什么在Java中没有大括号的另一个IF内允许使用IF块的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

通常在JAVA中,如果IF语句不带花括号,则在满足IF条件时只能执行一行,但是如果另一个IF块(内部IF)跟随初始IF,则不会触发错误,并且还有更多的台词.这怎么可能?

Normally in JAVA if an IF statement doesn't have curly brackets can have only one line that is executed when IF condition is met, however if another IF block (inner IF) follows the initial IF, then no error is triggered and there are more lines. How is this possible?

示例

if (true)
if (true)
   System.out.println("true");
else
   System.out.println("false");

推荐答案

通常在JAVA中,如果IF语句不带大括号,则在满足IF条件时只能执行一行,

Normally in JAVA if an IF statement doesn't have curly brackets can have only one line that is executed when IF condition is met,

更正.不带花括号的 if 语句只能有一个 statement ,该条件满足时才执行.而且 if 的语法类似于

Correction. An if statement without braces can have only one statement that is executed when the condition is met. And the syntax of if goes something like

if (<condition>) <statement>; [else <statement>;]

也就是说,如果有 else ,则它是 if 的一部分.都是声明.

That is, if there's an else, it's part of the if. It's all one statement.

没有错误的原因是因为这里没有歧义.(好吧,无论如何,不​​是编译器.)由于 else if 的一部分,因此它与最接近的 if 一起使用.因此,只要有适当的缩进,您就可以

The reason there's no error is because there's no ambiguity here. (Well, not to the compiler, anyway.) Since the else is part of the if, it goes with the closest if. So with proper indenting, you have

if (true)
    if (true)
       System.out.println("true");
    else
       System.out.println("false");

这篇关于为什么在Java中没有大括号的另一个IF内允许使用IF块的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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