繁体   English   中英

什么时候多线环体不需要花括号?

[英]When are curly braces not required for multi-line loop bodies?

为什么这段代码表现正常? 我被告知多行循环体应该总是有花括号

public class Sample {

    public static void main(String[] args)
    {
        int[] nums = {1,2,3,4,5,6,7,8,9,10};

        // print out whether each number is
        // odd or even
        for (int num = 0; num < 10; num++)
            if (num % 2 == 0)
                System.out.println(num + " is even");
            else
                System.out.println(num + " is odd");
    }
}

这里的诀窍是语句之间的区别。 循环体只会执行下一个语句 ,除非有花括号,在这种情况下循环将执行花括号内的整个块。 (正如在其他答案中所提到的,对每个循环和if语句使用花括号总是好的做法。这使代码更容易理解,更容易正确修改。)

根据您的具体示例:

java中的if-else语句被认为是单个语句。

此外,以下是有效的单行声明:

if(someBoolean)
    someAction(1);
else if (someOtherBoolean)
    someOtherAction(2);
else
    yetAnotherAction();

您可以根据需要添加任意数量的else-if,编译器仍然可以将其视为单个语句。 但是,如果您不使用else,则会将其视为单独的行。 例如:

for(int a=0; a<list.size; a++)
    if(list.get(a) == 1)
        someAction();
    if(list.get(a) == 2)
        someOtherAction();

这段代码实际上不会编译,因为第二个if语句超出了for循环的范围,因此int a不存在。

使用多个语句 (不是多行)时需要花括号。
但是,总是使用花括号是一种好习惯。
这可以避免在以后添加语句时出现错误。

If-else语句被认为是单个语句,因此代码有效。 但是,如果在If-else之后添加一行,那么该行将不被视为for循环的一部分。

例如 -

for (int num = 0; num < 10; num++)
        if (num % 2 == 0)
            System.out.println(num + " is even");
        else
            System.out.println(num + " is odd");
            System.out.println("Blah");

输出将是 -

0 is even
1 is odd
2 is even
3 is odd
4 is even
5 is odd
6 is even
7 is odd
8 is even
9 is odd
Blah

如果你的循环只有一个语句,那么添加花括号不会影响你的代码。 如果其他人一起被认为是一个声明与其他ifs之间,正如其他人已经提到的那样。 但是,如果没有大括号,则不会执行多个语句。

for (int i=0;i<5;i++)
   if (i<4)
   System.out.println("Hurray");
   System.out.println("Alas");

产量

Hurray
Hurray
Hurray
Hurray
Alas     //Exited the loop here

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM