在过去的几天里,我一直在研究这个程序,并且确切地知道我想做什么,只是不知道如何去做。基本上我有两个数组,一个是包含学生姓名的字符串,另一个数组是一个包含学生分数的 int。两个数组值都是用户输入的。最终,我想按从最高分到最低分的降序打印出相应的名称和分数。现在,我的问题在于代码的末尾,我一生都无法弄清楚如何使两个索引匹配以用于 println 目的(我已经评论了问题所在。我按降序打印分数从最高到最低,但我无法获得符合要求的名称。任何有关如何解决此问题的建议将不胜感激。
import java.util.Scanner;
public class TestArray
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
System.out.println("Enter the number of students in your class: ");
int number = input.nextInt();
System.out.println("Now enter the " + number + " students names");
String[] nameList = new String[number];
for (int i = 0; i < number; i++) {
nameList[i] = input.next();
}
System.out.println("Next, enter the score of each student: ");
int[] numGrades = new int[number];
for (int i = 0; i < number; i++) {
numGrades[i] = input.nextInt();
}
for (int i = 0; i < number; i++) {
int currentMax = numGrades[i];
int currentMaxIndex = i;
int currentNameIndex = i;
for (int j = i + 1; j < number; j++) {
if (currentMax < numGrades[j]) {
currentMax = numGrades[j];
currentMaxIndex = j; // index max
currentNameIndex = j;
}
}
if (currentMaxIndex != i) {
numGrades[currentMaxIndex] = numGrades[i];
numGrades[i] = currentMax;
}
if (currentNameIndex != i) {
nameList[currentNameIndex] = String.valueOf(nameList[i]);
// need nameList[i] to = the current index of the numGrades array HOW???
}
}
for (int i = 0; i < number; i++) {
System.out.println(nameList[i] + " had a score of " + numGrades[i]);
}
}
}