我的问题是关于
Java for语句,例如
- for (int i = 0; i < 10; ++i) {/* stuff */}
我不明白的是,我可以在括号中放入多少代码/什么样的代码(即我有int i = 0; i< 10;我在我的例子中) - 我真的不明白用于描述它的语言: http://java.sun.com/docs/books/jls/third_edition/html/statements.html#24588
基本上我的问题归结为要求翻译规范中的位看起来像:
ForInit:
StatementExpressionList
LocalVariableDeclaration
编辑:哇.我想真正的答案是“学会阅读并理解JLS中使用的符号 – 它被用于某种原因”.谢谢你的所有答案.
解决方法
StatementExpressionList和LocalVariableDeclaration都在页面的其他位置定义.我会在这里复制它们:
- StatementExpressionList:
- StatementExpression
- StatementExpressionList,StatementExpression
- StatementExpression:
- Assignment
- PreIncrementExpression
- PreDecrementExpression
- PostIncrementExpression
- PostDecrementExpression
- MethodInvocation
- ClassInstanceCreationExpression
和
- LocalVariableDeclaration:
- VariableModifiers Type VariableDeclarators
- VariableDeclarators:
- VariableDeclarator
- VariableDeclarators,VariableDeclarator
- VariableDeclarator:
- VariableDeclaratorId
- VariableDeclaratorId = VariableInitializer
- VariableDeclaratorId:
- Identifier
- VariableDeclaratorId [ ]
- VariableInitializer:
- Expression
- ArrayInitializer
进一步遵循语法没有多大意义;我希望它很容易阅读.
这意味着您可以在ForInit部分中使用任意数量的StatementExpressions(以逗号分隔)或LocalVariableDeclaration. LocalVariableDeclaration可以由任意数量的“variable = value”对组成,以逗号分隔,以其类型开头.
所以这是合法的:
- for (int i = 0,j = 0,k = 0;;) { }
因为“int i = 0,k = 0”是有效的LocalVariableDeclaration.这是合法的:
- int i = 0;
- String str = "Hello";
- for (str = "hi",i++,++i,sayHello(),new MyClass();;) { }
因为初始化程序中的所有随机内容都符合StatementExpressions.
由于在for循环的更新部分中允许使用StatementExpressionList,因此它也是有效的:
- int i = 0;
- String str = "Hello";
- for (;;str = "hi",new MyClass()) { }
你开始拍照吗?