【发布时间】:2013-09-05 19:46:53
【问题描述】:
这段代码运行良好:
public class Main {
public static void main(String[] args) {
long startTime = System.currentTimeMillis();
long endTime = startTime + 60000;
long index = 0;
while (true) {
double x = Math.sqrt(index);
long now = System.currentTimeMillis();
if (now > endTime) {
break;
}
index++;
}
System.out.println(index + " loops in one minute.");
}
}
然后,我尝试将其重写为for loop,但它陷入了无限循环。
public class Main {
public static void main(String[] args) {
long startTime = System.currentTimeMillis();
long endTime = startTime + 60000;
int i = 0;
for (long now = 0; now < endTime; i++) {
Math.sqrt(i);
now = System.currentTimeMillis();
System.out.println("now" + now);
System.out.println("end" + endTime);
}
}
System.out.println(i+"calculations done in one minute");
}
【问题讨论】:
-
您正在重置循环内
now的值。因此,now将始终小于endTime。 -
你的第二种方法是如何编译的?
System.out不属于任何方法。 -
不是死循环,等1分钟就行了。
-
@Jbird:
now设置为System.currentTimeMillis(),这就是它应该工作的原因。 -
输出是什么?应该有很多。也许是写输出导致它需要超过一分钟的时间?
标签: java for-loop while-loop infinite-loop