定义一个Student数组,其中保存学生的基本信息,包括姓名、学号、性别;分别保存三门课程的成绩。试编程对这三门课程的成绩降序排序,输出排序后的结果java
时间: 2023-12-06 14:39:38 浏览: 135
以下是 Java 代码实现:
```
import java.util.Arrays;
import java.util.Comparator;
class Student {
String name;
int id;
String gender;
int score1;
int score2;
int score3;
public Student(String name, int id, String gender, int score1, int score2, int score3) {
this.name = name;
this.id = id;
this.gender = gender;
this.score1 = score1;
this.score2 = score2;
this.score3 = score3;
}
public String toString() {
return name + "\t" + id + "\t" + gender + "\t" + score1 + "\t" + score2 + "\t" + score3;
}
}
public class Main {
public static void main(String[] args) {
Student[] students = {
new Student("张三", 1001, "男", 90, 80, 70),
new Student("李四", 1002, "女", 80, 70, 60),
new Student("王五", 1003, "男", 70, 60, 50),
new Student("赵六", 1004, "女", 60, 50, 40)
};
Arrays.sort(students, new Comparator<Student>() {
public int compare(Student s1, Student s2) {
int totalScore1 = s1.score1 + s1.score2 + s1.score3;
int totalScore2 = s2.score1 + s2.score2 + s2.score3;
return totalScore2 - totalScore1;
}
});
System.out.println("姓名\t学号\t性别\t成绩1\t成绩2\t成绩3");
for (Student student : students) {
System.out.println(student);
}
}
}
```
输出结果:
```
姓名 学号 性别 成绩1 成绩2 成绩3
张三 1001 男 90 80 70
李四 1002 女 80 70 60
王五 1003 男 70 60 50
赵六 1004 女 60 50 40
```
阅读全文