ZZULIOJ 1194: 總成績排序(結構體專題),Java
題目描述
有一學生成績表,包括學號、姓名、3門課程成績。請按如下規則排序:按總成績降序排序,若總成績相同,則按姓名升序排序。
輸入
首先輸入一個整數n(1<=n<=100),表示學生人數;
然后輸入n行,每行包含一個學生的信息:學號(12位)、姓名(不含空格且不超過20位),以及3個整數,表示3門課成績,數據之間用空格隔開。
輸出
輸出排序后的成績單,格式見輸出樣例。
樣例輸入 Copy
3
541207010188 Zhangling 89 78 95
541207010189 Wangli 85 87 99
541207010190 Fangfang 89 88 85
樣例輸出 Copy
541207010189 Wangli 85 87 99 271
541207010190 Fangfang 89 88 85 262
541207010188 Zhangling 89 78 95 262
import java.util.ArrayList;
import java.util.Collections;
import java.util.Scanner;class Student {String id;String name;int[] scores;public Student(String id, String name, int[] scores) {this.id = id;this.name = name;this.scores = scores;}public int getTotalScore() {return scores[0] + scores[1] + scores[2];}
}public class Main {public static void main(String[] args) {Scanner sc = new Scanner(System.in);int n = sc.nextInt();ArrayList<Student> students = new ArrayList<>();for (int i = 0; i < n; i++) {String id = sc.next();String name = sc.next();int[] scores = new int[3];for (int j = 0; j < 3; j++) {scores[j] = sc.nextInt();}students.add(new Student(id, name, scores));}Collections.sort(students, (s1, s2) -> {if (s1.getTotalScore() != s2.getTotalScore()) {return Integer.compare(s2.getTotalScore(), s1.getTotalScore()); // Descending by total score} else {return s1.name.compareTo(s2.name); // Ascending by name if total scores are the same}});for (Student student : students) {System.out.println(student.id + " " + student.name + " " + student.scores[0] + " " + student.scores[1] + " " + student.scores[2] + " " + student.getTotalScore());}}
}