gpt4 book ai didi

java - for循环没有运行到最后?

转载 作者:行者123 更新时间:2023-11-30 02:22:49 24 4
gpt4 key购买 nike

我正在做一项练习,需要一种方法来总结数据中所有电话号码的所有持续时间(即类似于来电显示)。我已经设法总结了持续时间,但并未打印所有数据。我一直试图弄清楚为什么会这样,但我无法理解它。任何帮助将不胜感激。下面是代码:

//initial code provided
public static void main(String[] args) {
String[] phoneNumbers = new String[100];
int[] callDurations = new int[phoneNumbers.length];
int size = 0;

size = addCall(phoneNumbers, callDurations, size, "555-555-5555", 137);
size = addCall(phoneNumbers, callDurations, size, "555-555-0000", 12);
size = addCall(phoneNumbers, callDurations, size, "555-555-1234", 26);
size = addCall(phoneNumbers, callDurations, size, "555-555-8888", 10);
size = addCall(phoneNumbers, callDurations, size, "555-555-8888", 10);
size = addCall(phoneNumbers, callDurations, size, "555-555-7777", 10);

}


public static int addCall(String[] phoneNumbers, int[] callDurations, int size, String newNumber, int newDuration) {
if (size >= phoneNumbers.length) {
System.out.println("Error adding " + newNumber + ": array capacity exceeded.");
} else {
phoneNumbers[size] = newNumber;
callDurations[size] = newDuration;
size++;
}

return size;
}

//the portion of code that I'm trying to write

public static void totalDurations(String[] phoneNumbers, int[]
callDurations, int size) {
String[] copyNum = new String[phoneNumbers.length];
int[] copyDur = new int[phoneNumbers.length];
int newSize = size;
int pos = 1; //counter for next available empty cell
copyNum[0] = phoneNumbers[0];
copyDur[0] = callDurations[0];

for (int i = 0; i < newSize; i++){
for (int j = 1; j < size; j++){
if (copyNum[i] != phoneNumbers[j]){
copyNum[i+pos] = phoneNumbers[j];
pos++;
}
else {
copyDur[i] += callDurations[j];
newSize = newSize -1;
}
}
System.out.println(copyNum[i] + ":" + copyDur[i]+ "s");
}
}

我当前的输出

Total Durations:
555-555-5555:137s
555-555-0000:12s
555-555-1234:26s
555-555-8888:20s

最佳答案

这是一些非常丑陋的代码,您肯定需要在调试器中运行它,但我很清楚错误出在该行

newSize = newSize - 1;

这会减少外部 for 循环中使用的变量。如果您只完成了六个元素中的四个,则意味着为其中两个输入了 else 子句。也许您打算减少 size 来代替?

想想你想在这里做什么。使用调试器,以您意想不到的方式查看哪里出了问题。纠正它们。

关于java - for循环没有运行到最后?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46385865/

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