1004. 成绩排名 (20)
时间限制
400 ms
内存限制
65536 kB
代码长度限制
8000 B
判题程序
Standard
作者
CHEN, Yue
读入n名学生的姓名、学号、成绩,分别输出成绩最高和成绩最低学生的姓名和学号。
输入格式:每个测试输入包含1个测试用例,格式为
第1行:正整数n
第2行:第1个学生的姓名 学号 成绩
第3行:第2个学生的姓名 学号 成绩
... ... ...
第n+1行:第n个学生的姓名 学号 成绩
其中姓名和学号均为不超过10个字符的字符串,成绩为0到100之间的一个整数,这里保证在一组测试用例中没有两个学生的成绩是相同的。
输出格式:对每个测试用例输出2行,第1行是成绩最高学生的姓名和学号,第2行是成绩最低学生的姓名和学号,字符串间有1空格。
输入样例:3 Joe Math990112 89 Mike CS991301 100 Mary EE990830 95输出样例:
Mike CS991301 Joe Math990112
-----------------------------------------------------------------------------------------------------------
import java.util.Scanner; import java.util.ArrayList;//引入列表数组 import java.util.Collections;//引入集合类,用集合类的静态方法给列表数组排序 public class PAT_B_1004//在PAT平台提交需要把类名改为Main { public static void main(String[] args) { Scanner in = new Scanner(System.in);//接收所有输入 int n = in.nextInt();//根据题目描述,输入中第一个是数字,表示后面要输入的行数 in.nextLine();//跳过回车键 ArrayList<Student> students = new ArrayList<Student>();//构建学生列表数组 for(int i = 0; i < n; i++) { String[] lineSplit = in.nextLine().split(" "); //调用String.split("String")函数,将每行的字符串按空格划分为3个字符串。 //将3个字符串(名字,学号,分数)分别传给构造函数,构造学生对象 students.add(new Student(lineSplit[0], lineSplit[1], Integer.parseInt(lineSplit[2]))); //调用Integer.parse("String")将字符串解析为数字。 } Collections.sort(students);//调用集合类的静态排序函数,默认升序 System.out.println(students.get(n-1));//输出成绩最好的学生信息 System.out.println(students.get(0));//输出成绩最差的学生信息 } } class Student implements Comparable<Student>//只有实现Comparable接口才能调用集合类的静态排序函数 {//构造一个学生对象,用来保存学生的名字,学号,分数 String name;//名字 String stuId;//学号 int score;//分数 public Student(String name, String stuId, int score) {//构造函数 this.name = name; this.stuId = stuId; this.score = score; } public int compareTo(Student other) {//需实现Comparable接口里的compareTo函数,才能调用集合类中的排序函数 return (this.score - other.score); } public String toString() {//根据题目要求,输出名字和学号 return (this.name + " " + this.stuId); } }