查找和排序
题目:输入任意(用户,成绩)序列,可以获得成绩从高到低或从低到高的排列,相同成绩
都按先录入排列在前的规则处理。
示例:
jack 70
peter 96
Tom 70
smith 67
从高到低 成绩
peter 96
jack 70
Tom 70
smith 67
从低到高
smith 67
jack 70
Tom 70
peter 96
输入描述:
输入多行,先输入要排序的人的个数,然后输入排序方法0(降序)或者1(升序)再分别输入他们的名字和成绩,以一个空格隔开
输出描述:
按照指定方式输出名字和成绩,名字和成绩之间以一个空格隔开
示例1
输入
3
0
fang 90
yang 50
ning 70
输出
fang 90
ning 70
yang 50
思路: 简单的使用排序就可以了:
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
while (scanner.hasNext()) {
List<Student> list = new ArrayList();
Student student;
int n = scanner.nextInt();
int type = scanner.nextInt();
for (int i = 0; i < n; i++) {
student = new Student();
String name = scanner.next();
student.setName(name);
int score = scanner.nextInt();
student.setScore(score);
list.add(student);
}
if (type == 1) {
Collections.sort(list, new Comparator<Student>() {
@Override
public int compare(Student o1, Student o2) {
return o1.getScore() - o2.getScore();
}
});
}
if (type == 0) {
Collections.sort(list, new Comparator<Student>() {
@Override
public int compare(Student o1, Student o2) {
return o2.getScore() - o1.getScore();
}
});
}
for (Student student1 : list) {
System.out.println(student1);
}
}
}
}
class Student {
private String name;
private int score;
public Student() {
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getScore() {
return score;
}
public void setScore(int score) {
this.score = score;
}
@Override
public String toString() {
return name + " " + score;
}
}