我很遗憾地问,但我在书中练习时遇到了麻烦,而且我不确定如何修复它.输入学生的姓名和分数后,我会找到最高和第二高分.但是我找不到找到两个最高分的正确方法.
我使用的当前方式有效,但是用户输入的分数从低到高,例如70,80和90.如果完成了90,80和70,它会对数字进行适当的排序.
有什么我可以改变/做/读让我走上正确的道路吗?
import java.util.Scanner;
public class StudentSort {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
// For finding highest scores with corresponding array
double firstHighest = 0;
int firstEntry = 0;
double secondHighest = 0;
int secondEntry = 0;
System.out.print("Enter the number of students: ");
int studentCount = input.nextInt();
// Length of arrays set
int[] studentScores = new int[studentCount];
String[] studentName = new String[studentCount];
// Go through loop to set scores and names of each student
for (int i = 0; i < studentCount; i++) {
System.out.print("Enter a student name: ");
studentName[i] = input.next();
System.out.print("Enter a student score: ");
studentScores[i] = input.nextInt();
}
// Find out the highest and second highest scores
// Problem with secondHighest/Entry
for (int i = 0; i < studentScores.length; i++) {
if (studentScores[i] > firstHighest) {
secondHighest = firstHighest;
firstHighest = studentScores[i];
firstEntry = i;
} else if (studentScores[i] > secondHighest) {
secondHighest = studentScores[i];
secondEntry = i;
}
}
System.out.println("Top two students: ");
System.out.println(studentName[firstEntry] + "'s score is " + firstHighest);
System.out.println(studentName[secondEntry] + "'s score is " + secondHighest);
}
}
Run Code Online (Sandbox Code Playgroud)
一如既往,感谢您提供的任何帮助.
secondEntry当您获得新的最高分时,您似乎忘了更新.行前:
firstEntry = i;
Run Code Online (Sandbox Code Playgroud)
尝试添加:
secondEntry = firstEntry;
Run Code Online (Sandbox Code Playgroud)