一个单行循环,在Java中有一对强制括号 [英] A single-line loop with a mandatory pair of braces in Java

查看:123
本文介绍了一个单行循环,在Java中有一对强制括号的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下代码段中的代码运行正常。它计算使用 int 类型的静态字段创建的对象数,它是 cnt

The code in the following snippet works just fine. It counts the number of objects created using a static field of type int which is cnt.

public class Main
{
    private static int cnt;

    public Main()
    {
        ++cnt;
    }

    public static void main(String[] args)
    {
        for (int a=0;a<10;a++)
        {
            Main main=new Main();
        }

        /*for (int a=0;a<10;a++)
            Main main=new Main();*/

        System.out.println("Number of objects created : "+cnt+"\n\n");
    }
}

它显示以下输出。

Number of objects created : 10

唯一的问题是当我从上面的中移除循环中的大括号时(请参阅注释 for loop),发出编译时错误,指示

The only question is that when I remove the pair of curly braces from the above for loop (see the commented for loop), a compile-time error is issued indicating


不是声明。

not a statement.

为什么在这种特殊情况下,即使循环只包含单个语句,一对大括号强制? / p>

Why in this particular situation, a pair of braces is mandatory even though the loop contains only a single statement?

推荐答案

当你声明一个变量时(在这种情况下 main ): / p>

When you declare a variable (main in this case):

Main main = new Main();

它不算作声明,即使它有副作用。为了使它成为一个恰当的陈述,你应该只做

it doesn't count as a statement, even if it has side-effects. For it to be a proper statement, you should just do

new Main();






那么为什么


So why is

... {
    Main main = new Main();
}

允许吗? {...} 是一段代码, 计为一个语句。在这种情况下, main 变量可以在声明之后但在结束括号之前使用。有些编译器忽略了它确实没有被使用的事实,其他编译器也会发出警告。

allowed? { ... } is a block of code, and does count as a statement. In this case the main variable could be used after the declaration, but before the closing brace. Some compilers ignore the fact that it's indeed not used, other compilers emit warnings regarding this.

这篇关于一个单行循环,在Java中有一对强制括号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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