gpt4 book ai didi

java - 将变量设置回零

转载 作者:塔克拉玛干 更新时间:2023-11-03 03:06:04 24 4
gpt4 key购买 nike

我正在使用亚马逊上的一本电子书自学 Java。我正在上一门对计算机进行“基准测试”的类(class)。它通过循环一分钟并计算结果来完成此操作。

它基本上不会在一分钟内显示任何内容,直到它完成。所以我做了一个小修改,每隔几秒显示一个点作为某种进度条。通常这是一件微不足道的事情,但有些地方不对劲,我也不知道是什么。

发生的事情是 miniIndex 将达到我指定的阈值,并打印 miniIndex 的值和一个句点。然后应该将 miniIndex 设置为零,以便计数器可以重新启动。但它不会重置,也不会再增加。这是非常奇怪的行为。

完整代码如下:

class Benchmark {
public static void main(String[] arguments) {

long startTime = System.currentTimeMillis();
long endTime = startTime + 60000;
long index = 0;

// My inner index
int miniIndex = 0;
//
while (true) {
double x = Math.sqrt(index);
long now = System.currentTimeMillis();
if (now > endTime){
break;
}
index++;
// my modification
miniIndex++;
if (miniIndex >= 5000) {
System.out.print(miniIndex + ".");
miniIndex = 0;
}
// end of my modification
}
System.out.println(index + " loops in one minute.");
}
}

最佳答案

我想你误解了你的 miniIndex++ 操作在做什么,因为它不是计算毫秒而是计算循环迭代的次数,这些迭代次数彼此相等.根据您希望发生的情况,我修改了您的代码以每 5 秒内执行一次 if 语句:

public static void main(String[] arguments) {

long startTime = System.currentTimeMillis();
long miniTime = startTime; //Declare miniTime equal to startTime
long endTime = startTime + 60000;
long index = 0;

while (true) {
double x = Math.sqrt(index);
long now = System.currentTimeMillis();
if (now > endTime){
break;
}
index++;

// my modification
//Current time minus last time the if executed and check if 5 seconds passed
if ((now - miniTime) >= 5000) {
miniTime = System.currentTimeMillis();
System.out.println("5 seconds have passed.");

//if you want to print the actual time elapsed every 5 seconds use this print
//System.out.println((now - startTime)/1000 + " seconds have passed.");
}
// end of my modification
}
System.out.println(index + " loops in one minute.");
}

请注意我现在如何比较 now 的当前时间并减去 miniTime 以检查它是否大于或等于 5000 毫秒。要使用时间,您必须以某种方式将它与时间相关联,在本例中为 System.currentTimeMillis() 和结果。数字本身(例如循环计数)永远不会是时间一致的。

一个循环可能执行数百万次,但只需要 3 秒。

示例输出:

5 seconds have passed.
5 seconds have passed.
5 seconds have passed.
5 seconds have passed.
5 seconds have passed.
5 seconds have passed.
5 seconds have passed.
5 seconds have passed.
5 seconds have passed.
5 seconds have passed.
5 seconds have passed.
16319642816 loops in one minute.

注意: 5 秒过去了。 打印了 11 次,因为在 60 秒标记处循环中断,所以最后一次打印没有打印。 (11 * 5 在前 55 秒是 55)。

关于java - 将变量设置回零,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57436270/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com