3 回答

TA贡献1828条经验 获得超3个赞
首先,我将获得与每个名称关联的索引列表:
HashMap<String, List<Integer>> map = new HashMap<String, List<Integer>>();
int index = 0;
for (String n: name) {
if (!map.containsKey(n)) {
map.put(n, new ArrayList<Integer>());
}
map.get(n).add(index);
index++;
}
然后,我将遍历每个名称:
for (String name : map.keySet()) {
得到他们的索引,并找到最大分数的索引:
List<Integer> indices = map.get(name);
int maxScore = 0, maxIndex = 0;
for (int index: indices) {
if (grades[index] > maxScore) {
maxIndex = index;
}
}
然后,我将从subjects数组中打印出相同的索引:
System.out.println(name + " did best in " + subject[index]);
}

TA贡献1820条经验 获得超10个赞
我将创建一个名为getStudentsHighestMark的方法,该方法将使用名称和成绩数据。该方法将遍历所有成绩,并且仅由相关学生考虑那些成绩。您需要一个int来跟踪您看到的该名称的最高成绩,以及该成绩所对应课程的字符串。遍历成绩后,只需返回课程名称即可获得该学生的最高分。像这样的东西:
public static void main(String[] args) {
String[] names = {"Peter", "James", "Roger", "Peter", "Jose"};
String[] subjects = {"English", "Math", "English", "Science", "Math"};
int[] grades = {96, 67, 78, 84, 100};
String petersBest = getStudentsHighestMark("Peter", names, subjects, grades);
System.out.println("Peter's best is: " + petersBest); //Peter's best is: English
String jamesBest = getStudentsHighestMark("James", names, subjects, grades);
System.out.println("James's best is: " + jamesBest); //James's best is: Math
String rogersBest = getStudentsHighestMark("Roger", names, subjects, grades);
System.out.println("Roger's best is: " + rogersBest); //Roger's best is: English
String josesBest = getStudentsHighestMark("Jose", names, subjects, grades);
System.out.println("Jose's best is: " + josesBest); //Jose's best is: Math
}
private static String getStudentsHighestMark(String name, String[] names, String[] subjects, int[] grades) {
int highestGrade = 0;
String bestCourse = "";
for(int i = 0; i < names.length; i++) {
if(names[i].equals(name) && grades[i] > highestGrade) {
highestGrade = grades[i];
bestCourse = subjects[i];
}
}
return bestCourse;
}
添加回答
举报