有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java使用迭代器运行数字(家庭作业)

我有一个我无法解决的任务。 这个问题可能已经被问了很多次,但我没有找到它,所以如果我真的在重复一个简单的问题,请原谅我


以下是任务:

Create a class named Benchmark. Write a method that counts from 1 to 8.000.000 by 1s. Every time the count reaches a multiple of 1.000.000 print that number on the screen. Use your watch to time how long the loop takes.
Alternatively, you can use the system clock to time the duration of your program. You can do this by using the static method currentTimeMillis in the class System. See the documentation of the JDK for a detailed explanation on using this method. The program should produce an output like this:

0
1000000
2000000
3000000
4000000
5000000
6000000
7000000
8000000


我发现我需要使用迭代器来完成这项工作。 但我的老师现在不在,我似乎不知道如何使用这个

再一次:很抱歉这个新手问题,如果有人能帮我解决这个。。我将永远感激;)

感谢阅读并提前感谢您提供的任何帮助


共 (1) 个答案

  1. # 1 楼答案

    只是:

    for (int i = 1; i <= 8000000; i++) {
        if (i % 1000000 == 0) {
            System.out.println(i);
        }
    }
    

    如果您还想测量时间:

    long start = System.currentTimeMillis();
    long end;
    for (int i = 1; i <= 8000000; i++) {
        if (i % 1000000 == 0) {
            end = System.currentTimeMillis();
            System.out.println(i);
            System.out.println((end-start));
            start = end;
        }
    }