题目源地址:https://pintia.cn/problem-sets/994805260223102976/problems/type/7
成绩排名:
读入 n(>0)名学生的姓名、学号、成绩,分别输出成绩最高和成绩最低学生的姓名和学号。
输入格式:
每个测试输入包含 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
刚学集合,便用的集合来做,可能绕弯了,代码如下:
package pat;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
/*
* 读入 n(>0)名学生的姓名、学号、成绩,分别输出成绩最高和成绩最低学生的姓名和学号。
*/
public class ScoreRanking {
@SuppressWarnings({ "unchecked", "rawtypes" })
public static void main(String[] args) {
List<Student> list = new ArrayList();
Scanner sc = new Scanner(System.in);
int n = Integer.parseInt(sc.nextLine());
addList(list, sc, n);
comparePrint(list, n);
sc.close();
}
private static void comparePrint(List<Student> list, int n) {
int maxIndex = 0;
int minIndex = 0;
int max = list.get(0).getScore();
int min = list.get(0).getScore();
for (int i = 1; i < n; i++) {
if (max < list.get(i).getScore()) {
max = list.get(i).getScore();
maxIndex = i;
}
if (min > list.get(i).getScore()) {
min = list.get(i).getScore();
minIndex = i;
}
}
String name = list.get(maxIndex).getName();
String id = list.get(maxIndex).getId();
System.out.println(name + " " + id);
String name1 = list.get(minIndex).getName();
String id1 = list.get(minIndex).getId();
System.out.println(name1 + " " + id1);
}
private static void addList(List<Student> list, Scanner sc, int n) {
for (int i = 0; i < n; i++) {
String str = sc.nextLine();
String strArr[] = str.split(" ");
// 判断长度是否满足
if (strArr[0].length() < 11 && strArr[1].length() < 11 && Integer.parseInt(strArr[2]) >= 0
&& Integer.parseInt(strArr[2]) <= 100) {
Student stu = new Student(strArr[0], strArr[1], Integer.parseInt(strArr[2]));
boolean bool = true;
// 判断是否重复
for (int j = 0; j < list.size(); j++) {
if (list.get(j).getScore() == Integer.parseInt(strArr[2])) {
bool = false;
break;
}
}
if (bool) {
list.add(stu);
}
}
}
}
}
class Student {
private String name;
private String id;
private int score;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public int getScore() {
return score;
}
public void setScore(int score) {
this.score = score;
}
public Student(String name, String id, int score) {
super();
this.name = name;
this.id = id;
this.score = score;
}
}