假如我今天有個500人的學生成績單排版為姓名,國文,英文,數學
A 56 70 80
B 70 80 40
..........
我想要先以總分為學生排序,若總分相同再以國文排序以此類推
請問我該如何處理呢?
以下為我目前初步的程式碼
import java.io.*;
public class scoretest{
public static void main(String[] args)throws Exception{
String[][] text=read("scores.txt",500,4);
System.out.println("-----每個同學的分數-----");
show(text);
System.out.println("-----學生排序-----");
sort(text);
}
public static String[][] read(String file,int i,int j){
try {
BufferedReader readfile=new BufferedReader(new FileReader(new File(file)));
String[][] text=new String[i][j];
String[] text2=new String[j];
int k=0;
String info="";
while(readfile.ready()){
info=readfile.readLine();
text2=info.split(",");
for(int a=0;a<text2.length;a++){
text[k][a]=text2[a];
}
k+=1;
}
readfile.close();
return text;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
public static void show(String[][] text){
for(int i=0;i<text.length;i++){
System.out.print(text[i][0]+":");
for(int k=1;k<text[i].length;k++){
System.out.print(text[i][k]+",");
}
System.out.println();
}
}
public static void sort(String[][] text){
}
1.先把資料物件化
2.建立排序器
3.排序
public static void main(String[] args) {
@lombok.Getter
@lombok.Setter
class Student {
// 名稱
public String name;
// 國文
public int scoreCht;
// 英文
public int scoreEng;
// 數學
public int scoreMath;
// 總分
public int totalScore;
}
// ====================================
// 讀取資料, 並轉為 Student 物件
// ====================================
String fileName = "c:/score.txt";
BufferedReader readfile = new BufferedReader(new FileReader(new File(fileName)));
List<Student> students = new ArrayList<Student>();
while (readfile.ready()) {
// 讀取行
String info = readfile.readLine();
// 將讀取資料物件化
Student student = new Student();
student.name = info; // 自己解析
student.scoreCht = info; // 自己解析
student.scoreEng = info; // 自己解析
student.scoreMath = info; // 自己解析
student.totalScore = student.scoreCht + student.scoreEng + student.scoreMath;
students.add(student);
}
readfile.close();
// ====================================
// 排序
// ====================================
// 設定排序器
// 先以總分排序
Comparator<Student> comparator = Comparator.comparing(Student::getTotalScore);
// 再以國文排序
comparator = comparator.thenComparing(Comparator.comparing(Student::getScoreCht));
// 再以英文排序
comparator = comparator.thenComparing(Comparator.comparing(Student::getScoreEng));
// 再以數學排序
comparator = comparator.thenComparing(Comparator.comparing(Student::getScoreMath));
// 排序
students = students.stream()
.sorted(comparator)
.collect(Collectors.toList());
// ====================================
// 列印
// ====================================
for (Student student : students) {
String info = String.format("%s: %s %s %s %s",
student.name,
student.totalScore,
student.scoreCht,
student.scoreEng,
student.scoreMath);
System.out.println(info);
}
}