gpt4 book ai didi

java - 如何从Java中的并行数组中删除重复项?

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

因此,我开始学习 Java,并想知道如何从源数组中一次性存储字符串和 int 类型的并行数组。例如,我有两个彼此并行的数组,一个将电话号码存储为字符串,另一个将通话持续时间存储为从每个电话号码获取的 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

(26 秒 + 28 秒)

在java中如何确保并行数组中没有存储重复项并获取每个电话号码的总持续时间,而不是将它们单独存储在数组中?

最佳答案

正如之前的答案中已经指出的,您可以使用 map - 将避免电话号码和通话持续时间( Java code to Prevent duplicate <Key,Value> pairs in HashMap/HashTable )中的重复。

或者,如果您想坚持使用 String 实现,则可以更改 findAllCalls() 方法中的逻辑。

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);
int i = 0, duration = 0;
while (i<size)
{
if(phoneNumbers[i].equals(targetNumber))
duration+=callDurations[i];
i++;
//System.out.println(phoneNumbers[match] + " duration: " + callDurations[match] + "s");
//match = find(phoneNumbers, size, match + 1, targetNumber);
}
System.out.println(targetNumber+" duration : "+duration+"s");
}

关于java - 如何从Java中的并行数组中删除重复项?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32684197/

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