【发布时间】:2013-04-16 13:27:01
【问题描述】:
我需要编写一个循环,每百万次迭代打印一次消息。我想让它运行 10 秒(时钟时间),看看打印了多少条语句。
我想我现在只是把自己打结了……
public class OneInAMillion{
public static void main(String []args){
long startTime = System.currentTimeMillis(); //time at start of execution
long endTime = startTime + 10000; //time at end of execution (10000 = 10 seconds)
int count = 1;
while(System.currentTimeMillis() < endTime) { //run this before 10 seconds is up
for (int i = 0; i < count; i++) {
if(i % 1000000 == 0) {
System.out.println("Iteration: " + count++); //print every millionth iteration
}
}
}
System.out.println("Time up!"); //print once loop finishes
}
}
【问题讨论】:
-
有什么问题?是否有错误,或者它只是不起作用?你试过什么?
-
你只能使用while循环并在里面增加i。
标签: java loops for-loop while-loop iteration