编写一个程序,把学生姓名和分数录入map,按分数显示学生名字。定义student类,封装学生姓名和考试分数。java
时间: 2024-01-21 19:17:44 浏览: 112
以下是Java代码实现:
```java
import java.util.*;
class Student {
private String name;
private int score;
public Student(String name, int score) {
this.name = name;
this.score = score;
}
public String getName() {
return name;
}
public int getScore() {
return score;
}
}
public class Main {
public static void main(String[] args) {
Map<Integer, String> map = new TreeMap<>(Collections.reverseOrder());
map.put(90, "Tom");
map.put(80, "Jerry");
map.put(95, "Alice");
map.put(70, "Bob");
for (Map.Entry<Integer, String> entry : map.entrySet()) {
System.out.println(entry.getValue() + ": " + entry.getKey());
}
List<Student> students = new ArrayList<>();
students.add(new Student("Tom", 90));
students.add(new Student("Jerry", 80));
students.add(new Student("Alice", 95));
students.add(new Student("Bob", 70));
Collections.sort(students, new Comparator<Student>() {
@Override
public int compare(Student o1, Student o2) {
return o2.getScore() - o1.getScore();
}
});
for (Student student : students) {
System.out.println(student.getName() + ": " + student.getScore());
}
}
}
```
这个程序首先使用 `Map` 存储学生姓名和分数,并按照分数从高到低排序输出。然后定义了一个 `Student` 类,封装学生姓名和考试分数,使用 `List` 存储学生对象,并按照分数从高到低排序输出。
阅读全文