用java写一串代码,创建一个学生类,姓名,年龄,语文分数,数学分数,英语分数,添加几条数据,再输出,要求定义一个排序规则,根据总分从高到低输出,如果总分相同,按语文成绩从高到低,如果语文也相同,按数学成从高到低排序,如果数学也相同,按照年龄的字典顺序排序,要求不能使用if语句
时间: 2024-04-19 11:29:28 浏览: 95
以下是一个使用 Java 编写的实现上述要求的代码:
```java
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
class Student {
private String name;
private int age;
private int chineseScore;
private int mathScore;
private int englishScore;
public Student(String name, int age, int chineseScore, int mathScore, int englishScore) {
this.name = name;
this.age = age;
this.chineseScore = chineseScore;
this.mathScore = mathScore;
this.englishScore = englishScore;
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
public int getChineseScore() {
return chineseScore;
}
public int getMathScore() {
return mathScore;
}
public int getEnglishScore() {
return englishScore;
}
public int getTotalScore() {
return chineseScore + mathScore + englishScore;
}
@Override
public String toString() {
return "Student{" +
"name='" + name + '\'' +
", age=" + age +
", chineseScore=" + chineseScore +
", mathScore=" + mathScore +
", englishScore=" + englishScore +
'}';
}
}
public class Main {
public static void main(String[] args) {
List<Student> students = new ArrayList<>();
students.add(new Student("Alice", 18, 80, 90, 95));
students.add(new Student("Bob", 20, 90, 85, 90));
students.add(new Student("Charlie", 19, 85, 85, 95));
Comparator<Student> comparator = Comparator.comparing(Student::getTotalScore)
.reversed()
.thenComparing(Student::getChineseScore, Comparator.reverseOrder())
.thenComparing(Student::getMathScore, Comparator.reverseOrder())
.thenComparing(Student::getAge);
Collections.sort(students, comparator);
for (Student student : students) {
System.out.println(student);
}
}
}
```
上述代码中,首先定义了一个 `Student` 类,包含了姓名、年龄、语文分数、数学分数和英语分数等属性。通过构造函数来初始化这些属性,并提供了相应的 getter 方法。`getTotalScore()` 方法用来计算学生的总分。
在 `Main` 类中,创建了一个 `List<Student>` 类型的对象 `students`,并添加了几条学生数据。然后使用 `Comparator` 来定义排序规则,首先按照总分从高到低排序,如果总分相同则按照语文成绩从高到低排序,如果语文成绩也相同则按照数学成绩从高到低排序,最后按照年龄的字典顺序排序。
使用 `Collections.sort()` 方法对学生列表进行排序,并通过循环遍历输出排序后的结果。
阅读全文