我的问题是关于Java for语句,例如
for (int i = 0; i < 10; ++i) {/* stuff */}
Run Code Online (Sandbox Code Playgroud)
我不明白的是,我可以在括号中放入多少代码/什么样的代码(即我int i = 0; i < 10; ++i在我的示例中的位置) - 我真的不明白用于描述它的语言:
http://java.sun.com/docs/books/jls/third_edition/html/statements.html#24588
基本上我的问题归结为要求翻译规范中的位看起来像:
ForInit:StatementExpressionList LocalVariableDeclaration
编辑:哇.我想真正的答案是"学会阅读并理解JLS中使用的符号 - 它被用于某种原因".谢谢你的所有答案.
Mic*_*ers 17
双方StatementExpressionList并LocalVariableDeclaration在页面上的其他地方定义.我会在这里复制它们:
StatementExpressionList:
StatementExpression
StatementExpressionList , StatementExpression
StatementExpression:
Assignment
PreIncrementExpression
PreDecrementExpression
PostIncrementExpression
PostDecrementExpression
MethodInvocation
ClassInstanceCreationExpression
Run Code Online (Sandbox Code Playgroud)
和
LocalVariableDeclaration:
VariableModifiers Type VariableDeclarators
VariableDeclarators:
VariableDeclarator
VariableDeclarators , VariableDeclarator
VariableDeclarator:
VariableDeclaratorId
VariableDeclaratorId = VariableInitializer
VariableDeclaratorId:
Identifier
VariableDeclaratorId [ ]
VariableInitializer:
Expression
ArrayInitializer
Run Code Online (Sandbox Code Playgroud)
进一步遵循语法没有多大意义; 我希望它很容易阅读.
它的意思是,你可以有两种任意数量的StatementExpressions,用逗号隔开,或一LocalVariableDeclaration中ForInit一节.并且a LocalVariableDeclaration可以由任意数量的" variable = value"对组成,以逗号分隔,以其类型开头.
所以这是合法的:
for (int i = 0, j = 0, k = 0;;) { }
Run Code Online (Sandbox Code Playgroud)
因为" int i = 0, j = 0, k = 0"是有效的LocalVariableDeclaration.这是合法的:
int i = 0;
String str = "Hello";
for (str = "hi", i++, ++i, sayHello(), new MyClass();;) { }
Run Code Online (Sandbox Code Playgroud)
因为初始化程序中的所有随机内容都符合条件StatementExpressions.
因为StatementExpressionList在for循环的更新部分允许,所以这也是有效的:
int i = 0;
String str = "Hello";
for (;;str = "hi", i++, ++i, sayHello(), new MyClass()) { }
Run Code Online (Sandbox Code Playgroud)
你开始拍照吗?
需要注意的是:我们希望在括号中看到非常简单,非常熟悉的内容.超越
for (int i = 0; i < n; i++)
Run Code Online (Sandbox Code Playgroud)
很可能会混淆未来读者的代码.有时你需要以相反的顺序迭代 - 即使是起始和结束条件也会给许多程序员带来麻烦(是n,n-1,n + 1?是> 0,> = 0,......?)
在某些情况下,需要精心制作.我只是说 - 在你去那里之前要小心,考虑更简单的表示.
基本上,对于一个简单的 FOR 循环:
for (startCondition; endCondition; increment)
Run Code Online (Sandbox Code Playgroud)
在 startCondition 中,设置用于运行循环的变量的起始值;在很多情况下,你会看到它就像我一样
int i = 0
Run Code Online (Sandbox Code Playgroud)
在 endCondition 中,您指定循环继续进行的比较。所以,如果你想在 i = 15 时停止循环,你可以输入
i <= 15
Run Code Online (Sandbox Code Playgroud)
或者
i != 15
Run Code Online (Sandbox Code Playgroud)
您还可以执行与布尔值比较之类的操作,例如
i == true
Run Code Online (Sandbox Code Playgroud)
在增量中,您指定计数器变量在每次循环后应增量的量。如果你想简单地加 1,你可以输入
i++
Run Code Online (Sandbox Code Playgroud)
通过 startCondition 和 endCondition 中的更多表达式以及多个计数器,您可能会变得更加复杂,但这是一个简单的 FOR 循环。