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

查看:38
本文介绍了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+"

");
    }
}

它显示以下输出.

Number of objects created : 10

唯一的问题是,当我从上面的 for 循环(参见注释的 for 循环)中删除一对大括号时,会发出编译时错误表示

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

不是声明.

为什么在这种特殊情况下,即使循环只包含一条语句,一对大括号是强制性的?

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

推荐答案

当你声明一个变量(在本例中为main)时:

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天全站免登陆