Java中的对象创建语句不允许使用单行循环。为什么? [英] Object creating statement in Java doesn't allow to use a single-line loop. Why?
问题描述
以下程序没有自己的重要性。它只计算使用类计数器内的静态字段使用for循环创建的对象数量,如下所示。
The following program has no importance of its own. It just counts the number of objects created through the use of a for loop using a static field inside the class Counter as shown below.
package temp;
final class Counter
{
private static int cnt;
public Counter()
{
cnt++;
}
public static int show()
{
return(cnt);
}
}
final public class Main
{
public static void main(String[] args)
{
for (int i=0;i<50;i++)
{
Counter counter=new Counter();
}
/*for (int i=0;i<50;i++)
Counter counter=new Counter();*/
System.out.print("\nNumber of objects constructed:->"+Counter.show()+"\n\n");
}
}
这里唯一的问题是注释for循环意味着与上面的for循环相同(同样的东西也适用于while循环)根本不起作用导致编译时错误,表明 not声明意味着在这种特殊情况下,即使for循环只包含一个语句,这对括号也是必需的!为什么?
The only question here is that the commented for loop means the same as the above for loop (the same thing is also applied to a while loop) doesn't work at all causing a compile-time error that indicates that "not a statement" means that in this particular situation, the pair of braces are mandatory even though the for loop contains only one statement! Why?
推荐答案
要理解为什么会发生这种情况,你必须看看 Java的块和语句语法。
To understand why this happens, you have to look at Java's Blocks and Statements syntax in the language specification.
A ForStatement定义为:
A ForStatement is defined as:
ForStatement:
for ( ForInitopt ; Expressionopt ; ForUpdateopt )
Statement
语句定义为:
Statement:
StatementWithoutTrailingSubstatement
LabeledStatement
IfThenStatement
IfThenElseStatement
WhileStatement
ForStatement
StatementWithoutTrailingSubstatement:
Block
EmptyStatement
ExpressionStatement
SwitchStatement
DoStatement
BreakStatement
ContinueStatement
ReturnStatement
SynchronizedStatement
ThrowStatement
TryStatement
然后,看看Block:
Then, looking at Block:
Block:
{ BlockStatementsopt }
BlockStatements:
BlockStatement
BlockStatements BlockStatement
BlockStatement:
LocalVariableDeclarationStatement
ClassDeclaration
Statement
你'请注意,在此规范中,LocalVariableDeclarationStatement无效,除非它在块中。但是,因为ForStatement要求它后跟一个语句,所以必须存在括号以使表达式有效。因此,任何局部变量声明在没有括号的循环中都是无效的。
You'll notice that, within this specification, LocalVariableDeclarationStatement is not valid unless it is in a block. But, because the ForStatement requires that it is followed by a statement, there MUST exist parenthesis in order to make the expression valid. As such, any local variable declaration would be invalid in the loop without the brackets.
这篇关于Java中的对象创建语句不允许使用单行循环。为什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!