用java写一个学生成绩排序
时间: 2024-01-16 11:02:17 浏览: 33
好的,以下是Java代码示例,用来对学生的成绩进行排序:
```
import java.util.*;
class Student implements Comparable<Student>{
int id;
String name;
int score;
public Student(int id, String name, int score) {
super();
this.id = id;
this.name = name;
this.score = score;
}
@Override
public int compareTo(Student s) {
if(this.score == s.score)
return this.name.compareTo(s.name);
else
return s.score - this.score;
}
@Override
public String toString() {
return "Student [id=" + id + ", name=" + name + ", score=" + score + "]";
}
}
public class SortStudents {
public static void main(String[] args) {
Student s1 = new Student(1, "Tom", 90);
Student s2 = new Student(2, "Jerry", 80);
Student s3 = new Student(3, "Teddy", 95);
List<Student> list = new ArrayList<>();
list.add(s1);
list.add(s2);
list.add(s3);
Collections.sort(list);
System.out.println(list);
}
}
```
以上代码会按照学生的分数进行降序排列,并且如果两个学生的分数相同,则按照姓名的字典序进行排序。
相关推荐
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)