因此,我开始学习 Java,并想知道如何从源数组中只存储一次 string 和 int 类型的并行数组。例如,我有两个相互平行的数组,一个将电话号码存储为字符串,另一个将通话的持续时间存储为从每个电话号码获取的 a/an int。
String[] phoneNumbers;
phoneNumbers = new String[100];
int[] callDurations = new int[phoneNumbers.length];
int size = 0;
phoneNumbers[0] = "888-555-0000";
callDurations[0] = 10;
phoneNumbers[1] = "888-555-1234";
callDurations[1] = 26;
phoneNumbers[2] = "888-555-0000";
callDurations[2] = 90;
phoneNumbers[3] = "888-678-8766";
callDurations[3] = 28;
size = 4;
我写了一个方法来查找特定电话号码的详细信息,例如特定呼叫“888-555-1234”的持续时间这是该方法以及我如何调用它:
public static void findAllCalls(String[] phoneNumbers, int[] callDurations, int size, String targetNumber) {
int match;
System.out.println("Calls from " + targetNumber + ":");
match = find(phoneNumbers, size, 0, targetNumber);
while (match >= 0) {
System.out.println(phoneNumbers[match] + " duration: " + callDurations[match] + "s");
match = find(phoneNumbers, size, match + 1, targetNumber);
}
}
System.out.println("\n\nAll calls from number: ");
findAllCalls(phoneNumbers, callDurations, size, "888-555-1234");
这段代码的输出是:
All calls from number:
Calls from 888-555-1234:
888-555-1234 duration: 26s
888-555-1234 duration: 28s
Process finished with exit code 0
而我想要得到的输出是:
All calls from number:
Calls from 888-555-1234:
888-555-1234 duration: 54s
Process finished with exit code 0
(26s + 28s)
在java中如何确保没有重复存储在并行数组中并获得每个电话号码的总持续时间而不是将它们分别放在数组中?