そこで、Java の学習を開始し、string 型と int 型の並列配列をソース配列から 1 回だけ格納する方法を考えていました。たとえば、互いに並列な 2 つの配列があり、1 つは電話番号を文字列として保存し、もう 1 つは通話時間を各電話番号から取得した 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 秒)
並列配列に重複が保存されていないことを確認し、配列に別々に持つのではなく、各電話番号の合計時間を取得するにはどうすればよいですか?