gpt4 book ai didi

java - 如果有人可以处理这个错误代码,我会很高兴,找不到问题所在

转载 作者:行者123 更新时间:2023-12-01 18:42:08 26 4
gpt4 key购买 nike

我的程序获取一个 worker 30 天每天一小时和一分钟的开始时间和结束时间,然后找到他工作最长的一天并将其设置为要显示的输出。问题(我认为)似乎出在 for 循环中,这是循环部分:

for (ti=1; ti<=3; ti++) {

System.out.println("Please enter the hours and minutes you started by this order.");
double hours1 = reader.nextDouble();
double mins1 = reader.nextDouble();

System.out.println("Please type the time you finished in hours and minutes by this order.");
double hours2 = reader.nextDouble();
double mins2 = reader.nextDouble();

double total = difference(hours1, mins1, hours2, mins2);

tdays.add(total);

if (tdays.get(ti) > tdays.get(ti - 1)) {
big = tdays.get(ti);
tday = ti;
}

}

错误代码:

    at java.base/jdk.internal.util.Preconditions.outOfBounds(Preconditions.java:64)
at java.base/jdk.internal.util.Preconditions.outOfBoundsCheckIndex(Preconditions.java:70)
at java.base/jdk.internal.util.Preconditions.checkIndex(Preconditions.java:248)
at java.base/java.util.Objects.checkIndex(Objects.java:373)
at java.base/java.util.ArrayList.get(ArrayList.java:425)
at Main.main(Main.java:24)

完整代码:```import java.util.*;公共(public)类主要{

static Scanner reader = new Scanner(System.in);
public static void main(String[] args) {

ArrayList<Double> tdays = new ArrayList<>();
int ti, tday=0;
double big=0;
for (ti=1; ti<=3; ti++) {

System.out.println("Please enter the hours and minutes you started by this order.");
double hours1 = reader.nextDouble();
double mins1 = reader.nextDouble();

System.out.println("Please type the time you finished in hours and minutes by this order.");
double hours2 = reader.nextDouble();
double mins2 = reader.nextDouble();

double total = difference(hours1, mins1, hours2, mins2);

tdays.add(total);

if (tdays.get(ti) > tdays.get(ti - 1)) {
big = tdays.get(ti);
tday = ti;
}

}

System.out.println("The worker has worked " + big + " hours on day number " + tday + ".");

}

public static double convertMin (double hours, double minutes) {

double totalmin;
hours = hours * 60;
totalmin = hours + minutes;

return totalmin;

}

public static double difference(double mins1, double hours1, double mins2, double hours2) {

double total1 = convertMin(hours1, mins1);
double total2 = convertMin(hours2, mins2);

return total2 - total1;

}

}

Thanks for any help!

最佳答案

您的问题是您只向列表添加一个元素,但随后您尝试访问索引“1”(这将是第二个元素)

我认为您可以通过添加检查是否 tdays.size() > 1 (或类似的内容)来解决此问题

我已将各行分开以向您显示导致错误的部分。

tdays.add(total);

Double a = tdays.get(ti); // this tries to access index 1, but there is only one element
Double b = tdays.get(ti - 1);
if (a > b) {
big = tdays.get(ti);
tday = ti;
}

关于java - 如果有人可以处理这个错误代码,我会很高兴,找不到问题所在,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59908139/

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