过去几天我一直在研究此程序,并确切知道我想要做什么,而不是如何去做。基本上我有两个数组,一个是包含学生姓名的字符串,另一个是包含学生成绩的int数组。这两个数组值都是用户输入的输入。最终,我想打印出相应的名称和分数,从最高分到最低分按降序排列。现在,我的问题在于代码的结尾,在这个代码中我无法理解如何让两个索引匹配println的用途(我已经评论了问题的出处在哪里,我打印的分数是下降顺序的从最高到最低的,但我不能得到遵守的名字。如何解决这个问题的任何建议,将不胜感激。如何获取字符串数组索引以匹配Int中的Int数组索引
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]);
}
}
}
如果您已经学过类,那么最好将分数和名称放入类中,并使用该类的单个对象数组。 – ApproachingDarknessFish