为什么在'for(...)之后添加分号会如此戏剧性地改变我的程序的含义?

Sai*_*Aye -1 java

我写了以下课程:

  public class TestOne {
     public static void main(String[] args) {
        int count = 0;
        for (int i = 0; i < 100; i++) {
          count++;
        }
        System.out.println(count);
     }
   }
Run Code Online (Sandbox Code Playgroud)

输出是100.

然后我添加了一个分号:

    public class TestOne {
     public static void main(String[] args) {
        int count = 0;
        for (int i = 0; i < 100; i++); {     // <-- Added semicolon
          count++;
        }
        System.out.println(count);
     }
   }
Run Code Online (Sandbox Code Playgroud)

输出是1.

结果令人难以置信.为什么这个添加分号会如此戏剧性地改变我的程序的含义?

Jon*_*uis 8

分号使for循环的主体变空.它相当于:

public class TestOne {
     public static void main(String[] args) {
        int count = 0;

        for (int i = 0; i < 100; i++) { }

        count++;
        System.out.println(count);
     }
   }
Run Code Online (Sandbox Code Playgroud)


pb2*_*b2q 7

这不是一个错误.分号成为for循环体中唯一的"语句" .

写另一种方式,以便更容易看到:

for (int i = 0; i < 100; i++)
    ;

{
    count++;
}
Run Code Online (Sandbox Code Playgroud)

由于分号,该块count++变为具有单个语句的裸块,该语句根本不与for循环相关联.因此,此块及其count++内部仅执行一次.

这是语法上有效的java.for (int i = 0; i < 100; i++);相当于:

for (int i = 0; i < 100; i++)
{ ; } // no statement in the body of the loop.
Run Code Online (Sandbox Code Playgroud)

for由于循环增量语句或终止条件中的副作用,这种形式的循环可能很有用.例如,如果您想编写自己的内容indexOfSpace来查找空格字符的第一个索引String:

int idx;

// for loop with no body, just incrementing idx:
for (idx = 0; string.charAt(idx) != ' '; idx++);

// now idx will point to the index of the ' '
Run Code Online (Sandbox Code Playgroud)