Java中带有一对强制的花括号的单行循环

下面的代码中的代码工作得很好。 它计算使用inttypes的静态字段cnt创build的对象的数量。

 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循环中删除了一对花括号(参见注释循环)时,会发出编译时错误

不是一个声明。

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

当你声明一个variables(在这个例子中是main )时:

 Main main = new Main(); 

即使它有副作用,也不算作声明。 因为这是一个恰当的说法,你应该这样做

 new Main(); 

那么为什么

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

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

用一个新语句创build一个单行块是有意义的。 没有任何意义的是在一个单行块中保存一个刚刚创build的对象的引用,因为你不能从范围之外访问variablesmain。

也许(只是我的猜测)编译器迫使你明确地input括号,因为在这种情况下保持引用没有意义,希望你能意识到无用的引用。

定义如下。

 BasicForStatement: for ( ForInitopt ; Expressionopt ; ForUpdateopt ) Statement ForStatementNoShortIf: for ( ForInitopt ; Expressionopt ; ForUpdateopt ) StatementNoShortIf ForInit: StatementExpressionList LocalVariableDeclaration ForUpdate: StatementExpressionList StatementExpressionList: StatementExpression StatementExpressionList , StatementExpression 

块定义如下。

块是大括号内的一系列语句,局部类声明和局部variables声明语句。

 Block: { BlockStatementsopt } BlockStatements: BlockStatement BlockStatements BlockStatement BlockStatement: LocalVariableDeclarationStatement ClassDeclaration Statement 

报表定义如下。

 Statement: StatementWithoutTrailingSubstatement LabeledStatement IfThenStatement IfThenElseStatement WhileStatement ForStatement StatementWithoutTrailingSubstatement: Block EmptyStatement ExpressionStatement AssertStatement SwitchStatement DoStatement BreakStatement ContinueStatement ReturnStatement SynchronizedStatement ThrowStatement TryStatement StatementNoShortIf: StatementWithoutTrailingSubstatement LabeledStatementNoShortIf IfThenElseStatementNoShortIf WhileStatementNoShortIf ForStatementNoShortIf 

根据规范, LocalVariableDeclarationStatement (查看块部分)是无效的,如果它没有在块内声明。 因此,除非使用一对大括号,否则以下for循环会报告您的问题中提到的编译时错误“ 不是语句 ”。

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