sam*_*can 0 java iteration loops for-loop while-loop
我需要编写一个循环,每百万次迭代打印一次消息.我想让它运行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
}
}
Run Code Online (Sandbox Code Playgroud)
你在循环中有一个循环.想想每个循环的作用 - 第一个循环将继续,直到超过10秒.另一个将简单地从0开始到1,并且在while循环的下一次迭代中,它将从0变为2,然后变为0到3,依此类推.它也会在0(因此很多)时打印,因为0%1000000为0.
尝试将它们组合成一个循环.这可以通过去除while循环并且仅具有while循环条件的for循环来完成,如下所示:
public static void main(String[] args) {
long endTime = System.currentTimeMillis() + 10000; //time at end of execution (10000 = 10 seconds)
for (int i = 1; System.currentTimeMillis() < endTime; i++) {
if(i % 1000000 == 0) {
System.out.println("Iteration: " + i/1000000); //print every millionth iteration
}
}
System.out.println("Time up!"); //print once loop finishes
}
Run Code Online (Sandbox Code Playgroud)
请注意,count永远是i/1000000,所以我摆脱了它.