Java为什么我不能在for循环之外初始化变量的起始值?
有什么原因不能在for循环外初始化变量的起始值吗?当我这样做时:
public static void main(String[] args) {
int userInt = 1;
int ender = 10;
for (userInt; userInt < ender; userInt++) {
System.out.println(userInt);
我收到一个语法错误,指出需要为userInt分配一个值,即使我已经为它分配了一个值1。当我这样做时:
public static void main(String[] args) {
int userInt;
int ender = 10;
for (userInt = 1; userInt < ender; userInt++) {
System.out.println(userInt);
错误消失了。这是什么原因
# 1 楼答案
Java
for loop
的通用语法如下:这意味着您不能只在块中写下变量名。如果你想使用一个已经定义好的变量,就让它emtpy
这应该对你有用:
# 2 楼答案
问题是
for
语句需要一个表达式根据language spec的说法:
然后:
正如您看到的basic for语句一样,第一个元素是可选的初始化,即语句或局部变量声明
该声明是以下声明之一:
在您的示例中
userInt = 1
是一个Assignment
,而userInt
与StatementExpression
列表上的任何元素都不匹配,这会导致编译错误