Java - 为什么我不能在for循环之外初始化变量的起始值?

doc*_*ugh 1 java for-loop

有没有理由我不能在for循环之外初始化变量的起始值?当我这样做:

    public static void main(String[] args) {

    int userInt = 1;
    int ender = 10;

    for (userInt; userInt < ender; userInt++) {
        System.out.println(userInt);
Run Code Online (Sandbox Code Playgroud)

我收到一个语法错误,指出userInt需要分配一个值,即使我已经为它指定了值1.当我这样做时:

public static void main(String[] args) {

    int userInt;
    int ender = 10;

    for (userInt = 1; userInt < ender; userInt++) {
        System.out.println(userInt);
Run Code Online (Sandbox Code Playgroud)

错误消失了.这是什么原因?

Den*_*hel 7

Java的通用语法for loop如下:

for ( {initialization}; {exit condition}; {incrementor} ) code_block;
Run Code Online (Sandbox Code Playgroud)

这意味着你不能只在inizalization块中写下变量名.如果你想使用一个已定义的变量,你只需要它就可以了.

这应该适合你:

for (; userInt < ender; userInt++) {
        System.out.println(userInt);
}
Run Code Online (Sandbox Code Playgroud)

  • @TomFang:回答你的原始尝试失败的原因:这是因为"`userInt;`"不是一个有效的语句,而这正是你试图在原来的`for`循环中评估的. (3认同)