我正在尝试从3个数组中使用索引时获得一个值?

name[5] = {Peter, James, Roger, Peter, Josę};


subject[5] = {English, Math, English, Science, Math};


grade[5] = {96, 67, 78, 84, 100};

我要在这里实现的目标是使主题获得个人的最高分。请注意名称Array中名称的重复,这是同一个人。我试图做的是使用一个映射来获得结果,但是对于3个数组,对于我目前拥有的Java级别来说,这是非常棘手的。我想获取学生的姓名,将其与他们的成绩相匹配,然后选择成绩最高的学科,因此基本上,每个学生的名字的回报将是一个值。像这样


英语数学英语数学


弑天下
浏览 162回答 3
3回答

倚天杖

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

拉莫斯之舞

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

相关分类

Python