为什么在’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); } }
输出为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); } }
输出为1
。
结果令人难以置信。 为什么这个添加的分号会如此戏剧性地改变我的程序的含义?
这不是一个错误。 分号成为for
循环体中唯一的“语句”。
写另一种方式,以便更容易看到:
for (int i = 0; i < 100; i++) ; { count++; }
带有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.
由于循环增量语句或终止条件中的副作用,这种forms的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 ' '
分号使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); } }
通过添加分号,您将声明没有块循环的for语句。
这导致count++
仅在传递时执行一次,而不是在循环时执行100次。
用分号表示for循环块结束,内部没有指令。
然后你只增加一次计数,这就是输出为1的原因
public class TestOne { public static void main(String[] args) { int count = 0; for (int i = 0; i < 100; i++) ; { count++; } System.out.println(count); } }
分号是一个空语句,是一个有效的语句 。 您当前的循环仅对该“空语句”( ;
)起作用,因此您没有看到关于循环的count
有任何变化。
在循环之后,语句count++
被执行一次,因此你看到结果为’1’。 如果未使用{ }
指定循环体,则循环后的第一个语句将被视为循环的一部分。 在你的第二种情况下,它是空的陈述。
它相当于:
for (int i = 0; i < 100; i++) { ; //any empty valid statement } count++;
在迭代结束后,您将递增计数值
在for循环之后,您使用了半冒号,因此您的for循环结束
for(int i = 0; i <100; i ++);
{count ++; }
count增量不在for循环中。 它在循环之外;