標籤:arrays turn china integer compareto 整數 gen author 用例
讀入n名學生的姓名、學號、成績,分別輸出成績最高和成績最低學生的姓名和學號。
輸入格式:每個測試輸入包含1個測試案例,格式為
第1行:正整數n 第2行:第1個學生的姓名 學號 成績 第3行:第2個學生的姓名 學號 成績 ... ... ... 第n+1行:第n個學生的姓名 學號 成績
其中姓名和學號均為不超過10個字元的字串,成績為0到100之間的一個整數,這裡保證在一組測試案例中沒有兩個學生的成績是相同的。
輸出格式:對每個測試案例輸出2行,第1行是成績最高學生的姓名和學號,第2行是成績最低學生的姓名和學號,字串間有1空格。
輸入範例:
3Joe Math990112 89Mike CS991301 100Mary EE990830 95
輸出範例:
Mike CS991301Joe Math990112
1 import java.lang.reflect.Array; 2 import java.util.ArrayList; 3 import java.util.Arrays; 4 import java.util.Collections; 5 import java.util.List; 6 import java.util.Scanner; 7 /** 8 * 使用容器自訂排序 9 * @author China10 *11 */12 13 public class Main {14 public static void main(String[] args) {15 List<Student> stds = new ArrayList<Student>();16 Scanner input = new Scanner(System.in);17 int num = Integer.parseInt(input.nextLine());18 while(num>0){19 String str = input.nextLine();20 //System.out.println(str);21 String[] temp = str.split(" ");22 Student std = new Student();23 std.name = temp[0];24 std.stuId = temp[1];25 std.score = Integer.parseInt(temp[2]);26 stds.add(std);27 num--;28 }29 Collections.sort(stds);30 System.out.println(stds.get(0).name+" "+stds.get(0).stuId);31 System.out.println(stds.get(stds.size()-1).name+" "+stds.get(stds.size()-1).stuId);32 }33 34 }35 class Student implements Comparable<Student>{36 String name;37 String stuId;38 int score;39 @Override40 public String toString() {41 return "Student [name=" + name + ", stuId=" + stuId + ", score=" + score + "]";42 }43 @Override44 public int compareTo(Student o) {45 // TODO Auto-generated method stub46 return -(score-o.score);47 }48 49 }
PAT 1004. 成績排名 (20) JAVA