比较
for (<init stmnt> <boolean expr>; <incr stmnt>) {
<body statements>
}
到
<init stmnt>;
while (<boolean expr>) {
<body statements>
<incr stmnt>
}
当上述两个循环不能等价时,我们能找到一个例子吗?
最佳答案
每当您使用 continue;
循环内的语句,你不会得到相同的效果。
在 for 循环中,continue 语句导致 <incr stmnt>
被执行。但是在你的 while 循环中,它将被跳过,因为它发生在 continue;
之后。
看看下面的两个循环:
for (int i = 0; i < 10; i++) {
if (i%2 == 0) {
continue;
}
System.out.println(i);
}
int i = 0;
while (i < 10) {
if (i%2 == 0) {
continue;
}
System.out.println(i);
i++;
}
for 循环将打印 1、3、5、7、9(中间换行)。
while 循环将永远循环并且永远不会打印任何东西。
关于java - 是否有这些 for 和 while 循环不等效的示例?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32879034/