我很抱歉問,但我在書中練習時遇到了問題,而且我不確定如何解決此問題。輸入學生的名字和成績後,我會找到最高和第二高的分數。但是我找不到找到兩個最高分的正確方法。對數組中的兩個最高數字進行排序
我使用的作品目前的方式,但是用戶輸入的分數從低到高,例如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);
}
}
與往常一樣,我感謝您提供任何幫助。
我建議使用調試器在程序進行時檢查變量的值,或者添加一個'println'語句來顯示這些中間值。通過這種方式,您可以比較您期望發生的情況和實際發生的情況。 – 2012-03-19 20:28:57
什麼不正確? (錯誤的輸出,錯誤信息,...) – talnicolas 2012-03-19 20:29:38
只是按降序排列你的數組,並選擇前兩個條目(對不起,我處於「Captain Obvious」心情) – 2012-03-19 20:29:41