[英]Java - Why can't I initialize the start value of a variable outside of a for loop?
Is there a reason why I can't initialize the start value of a variable outside of a for loop? 我为什么不能在for循环之外初始化变量的起始值? When I do this: 当我这样做时:
public static void main(String[] args) {
int userInt = 1;
int ender = 10;
for (userInt; userInt < ender; userInt++) {
System.out.println(userInt);
I receive a syntax error stating that userInt needs to be assigned a value, even though I've already assigned it a value of 1. When I do this instead: 我收到语法错误,指出即使已经为userInt分配了一个值1,也需要为其分配一个值。当我这样做时:
public static void main(String[] args) {
int userInt;
int ender = 10;
for (userInt = 1; userInt < ender; userInt++) {
System.out.println(userInt);
The error goes away. 错误消失了。 What is the reason for this? 这是什么原因呢?
The generic syntax for a Java for loop
is as follows: Java for loop
的通用语法如下:
for ( {initialization}; {exit condition}; {incrementor} ) code_block;
This mean you can not just write down a variable name in the inizalization block. 这意味着您不能只在inizalization块中写下变量名称。 If you want to use an already defined variable, you just let it emtpy. 如果要使用已经定义的变量,只需将其空。
This should work for you: 这应该为您工作:
for (; userInt < ender; userInt++) {
System.out.println(userInt);
}
The problem is that the for
statement expects an expression. 问题是for
语句需要一个表达式。
According to the language spec : 根据语言规范 :
ForStatement:
BasicForStatement
EnhancedForStatement
And then: 接着:
BasicForStatement:
for ( ForInitopt ; Expressionopt ; ForUpdateopt ) Statement
ForStatementNoShortIf:
for ( ForInitopt ; Expressionopt ; ForUpdateopt ) StatementNoShortIf
ForInit:
StatementExpressionList
LocalVariableDeclaration
ForUpdate:
StatementExpressionList
StatementExpressionList:
StatementExpression
StatementExpressionList , StatementExpression
As you see the basic for statement, first element is optional initialization, which is either statement or local variable declaration . 如您所见,基本的for语句是第一个元素是可选的初始化,它可以是statement或局部变量声明 。
The statement is one of : 该语句是以下之一:
StatementExpression:
Assignment
PreIncrementExpression
PreDecrementExpression
PostIncrementExpression
PostDecrementExpression
MethodInvocation
ClassInstanceCreationExpression
In your example userInt = 1
is an Assignment
, while just userInt
doesn't match any of elements on the StatementExpression
list, which causes compilation error. 在您的示例中, userInt = 1
是一个Assignment
,而仅userInt
与StatementExpression
列表中的任何元素都不匹配,这会导致编译错误。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.