[英]Error while declaring a variable inside for-loop along with print statement
I was trying to learn how for-loop works, so I made such a code. 我试图学习for循环的工作原理,所以我编写了这样的代码。
for(System.out.println("hi"),int i=0;i<5;System.out.println("yo"),i++)
{
System.out.println("teapot");
}
This way I can understand, which part of for-loop is being executed when. 通过这种方式,我可以了解何时执行for循环的哪一部分。 But I am getting an error in the first line stating ".class expected".
但是我在第一行指出“ .class期望”时出现错误。 Maybe this simply means, I cannot declare a variable in the first line.
也许这只是意味着,我无法在第一行中声明变量。 So I reworked it, and now it works perfectly.
因此,我对其进行了重新设计,现在它可以完美运行了。
int i;
for(System.out.println("hi"),i=0;i<5;System.out.println("yo"),i++)
{
System.out.println("teapot");
}
But I don't understand why I cannot declare a variable in the first line. 但是我不明白为什么我不能在第一行中声明一个变量。
The syntax of a basic for loop is: 基本的for循环的语法为:
BasicForStatement:
for ( [ForInit] ; [Expression] ; [ForUpdate] ) Statement
BasicForStatementNoShortIf:
for ( [ForInit] ; [Expression] ; [ForUpdate] ) StatementNoShortIf
ForInit:
StatementExpressionList
LocalVariableDeclaration
In other words: the first bit of the for
can contain either a list of statement expressions , or local variable declarations, but not both. 换句话说:
for
的第一位可以包含语句表达式列表或局部变量声明,但不能同时包含两者。
System.out.println("hi")
is a statement expression (because it's a method invocation expression); System.out.println("hi")
是一个语句表达式(因为它是一个方法调用表达式); int i=0
is not a statement expression (because it's not an expression); int i=0
不是语句表达式(因为它不是表达式); i=0
is a statement expression, because it's an assignment. i=0
是一个语句表达式,因为它是一个赋值。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.