大家好,我在为作业获取正确输出时遇到问题。我正在寻找一种将一组元素从一个并行数组(包含一个字符串--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-1234";
callDurations[2] = 2;
size = 3;
我想创建一个从原始数组(phoneNumber 和 callDuration)创建新的并行数组对的方法。这个方法将被称为 totalDuration,它不会返回任何值(void)。它会检查当前数组中的数字是否在新数组中,如果是,它只会将任何重复的持续时间添加到当前持续时间。如果不是,它将向 NewNumber 数组添加一个新元素,并向 NewDuration 数组添加一个元素。
public static int find(String[] list, int size, int start, String target) {
int pos = start;
while (pos < size && !target.equals(list[pos])) {
pos++;
}
if (pos == size)
pos = -1;
return pos;
}
此查找方法将用于检查电话号码是否已放置在新数组中,如果是,则确定该号码的位置。
例如,如果数组包含
phoneNumbers[0] = "888-555-0000";
callDurations[0] = 10;
phoneNumbers[1] = "888-555-1234";
callDurations[1] = 26;
phoneNumbers[2] = "888-555-1234";
callDurations[2] = 2;
打印“888-555-1234”的呼叫详细信息如下所示:
all calls from:
Calls from 888-555-1234:
888-555-1234 duration: 26s
888-555-1234 duration: 2s
新方法的输出应该是(26s +2s):
all calls from:
Calls from 888-555-1234:
888-555-1234 duration: 28s
我试图用这段代码解决它,但它给出了错误的输出:
public static void totalDurations(String[] phoneNumbers, int[] callDuration, int size, String target) {
String[] NewNumbers;
int[] NewDuration;
int pos;
NewNumbers = new String[phoneNumbers.length];
NewDuration = new int[callDuration.length];
pos = find(phoneNumbers,size, 0,target);
while(pos < size && !target.equals(phoneNumbers[pos])) {
NewNumbers[pos] = phoneNumbers[pos];
NewDuration[pos] = callDuration[pos];
System.out.println(NewNumbers[pos] + "duration" + NewDuration[pos] +"s");
}
}
不相关 我用来获取每个呼叫的所有详细信息的代码是我的方法“findAllCalls”
public static void findAllCalls(String[] phoneNumbers, int[] callDurations, int size, String targetNumber) {
int matchPos;
System.out.println("Calls from " + targetNumber + ":");
matchPos = find(phoneNumbers, size, 0, targetNumber);
while (matchPos >= 0) {
System.out.println(phoneNumbers[matchPos] + " duration: " + callDurations[matchPos] + "s");
matchPos = find(phoneNumbers, size, matchPos + 1, targetNumber);
}
}
System.out.println("\n all calls from: ");
findAllCalls(phoneNumbers,callDurations,size,"888-555-1234");
任何更正将不胜感激提前。