So, I started learning Java and was wondering how parallel arrays of string and int type could be stored exactly once from the source arrays. For example, I have two arrays parallel to each other, one stores the Phone number as a string and the other stores the duration of the calls as a/an int gotten from each phone number.
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;
I wrote a method to find the details of a specific phone number, such as the duration of the specific call "888-555-1234" Here is the method and how I called it:
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");
The output of this code is:
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
Whereas,the output I want to get instead is:
All calls from number:
Calls from 888-555-1234:
888-555-1234 duration: 54s
Process finished with exit code 0
(26s + 28s)
How is it possible in java to make sure there are no duplicates stored in a parallel array and get total duration for each phone number instead of having them separately in the arrays?
As already stated in the answers before, you can use a map - will avoid duplicates in both phoneNumber and callDuration (Java code to Prevent duplicate <Key,Value> pairs in HashMap/HashTable).
Or, if you want to stick with the String implementation, you can change the logic in the findAllCalls() method.
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");
}