gpt4 book ai didi

java - 从随机持续时间获取平均值

转载 作者:太空宇宙 更新时间:2023-11-04 10:28:06 25 4
gpt4 key购买 nike

我试图在这段代码的末尾打印持续时间的最大值、最小值和平均值,但我不太确定如何将随机持续时间存储在特定数组中以便在最后显示它。下面是代码:

public void test(){
int max;
int average;
int min;

long duration=2;
try
{ System.out.println("Bus Needs Cleaning" + "\n");
Thread.sleep(1000);
System.out.println("Bus getting cleaned");
Thread.sleep(1000);
duration = (long)(Math.random()*20);
TimeUnit.SECONDS.sleep(duration);

}
catch(InterruptedException iex)
{
}

System.out.println("Cleaner completed cleaning in" + duration + "Seconds");
System.out.println("Bus Leaves");

System.out.println("Average Waiting Time: " + average + " | Maximum: "+ max + " | Minimum" + min +"\n");

}

任何帮助将不胜感激,谢谢!

编辑:有 5 辆公交车进出,显示不同的持续时间,并且它们都经过清洁阶段

最佳答案

请尝试一下这个。据我了解

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

public class BusRandom {

public static void main(String[] args) {
new BusRandom().test();
}

public void test() {
long max = 0;
double average = 0;
long min = Long.MAX_VALUE;
int totalBuses=5;//change accordinly
List<Long> randomList = new ArrayList<>();
long duration = 2;
try {
for (int i = 0; i <totalBuses; i++) {
System.out.println("Bus Needs Cleaning" + "\n");
Thread.sleep(1000);
System.out.println("Bus getting cleaned");
Thread.sleep(1000);
duration = (long) (Math.random() * 20);
randomList.add(duration);
TimeUnit.SECONDS.sleep(duration);
System.out.println("Cleaner completed cleaning in" + duration + "Seconds");
System.out.println("Bus Leaves");
max=max>duration?max:duration;
min=min<duration?min:duration;
}
} catch (InterruptedException iex) {
}
double sum=0;
for(long l:randomList){
sum+=l;
}
average=(double) (sum/randomList.size());
System.out.println("Average Waiting Time: " + average + " | Maximum: " + max + " | Minimum" + min + "\n");

}
}

关于java - 从随机持续时间获取平均值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50315472/

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