Java定义一个Student数组,其中保存学生的基本信息,包括姓名、学号、性别,还分别保存三门课程的成绩及三门课程对应的学分。试编程计算这三门课程的学分积,并按学分积的降幂进行排序,输出排序后的结果。
时间: 2023-06-12 07:04:37 浏览: 338
以下是Java代码实现:
```java
import java.util.*;
public class Main {
public static void main(String[] args) {
// 定义学生数组并初始化
Student[] students = {
new Student("张三", "001", "男", 80, 90, 85, 4, 5, 3),
new Student("李四", "002", "女", 90, 95, 92, 4, 5, 3),
new Student("王五", "003", "男", 85, 87, 89, 4, 5, 3),
new Student("赵六", "004", "女", 92, 88, 90, 4, 5, 3),
new Student("钱七", "005", "男", 78, 80, 82, 4, 5, 3)
};
// 计算学分积并排序
Arrays.sort(students, new Comparator<Student>() {
@Override
public int compare(Student s1, Student s2) {
double credit1 = s1.getCreditProduct();
double credit2 = s2.getCreditProduct();
if (credit1 > credit2) {
return -1;
} else if (credit1 < credit2) {
return 1;
} else {
return 0;
}
}
});
// 输出排序结果
for (Student student : students) {
System.out.println(student);
}
}
}
class Student {
private String name;
private String id;
private String gender;
private int score1;
private int score2;
private int score3;
private int credit1;
private int credit2;
private int credit3;
public Student(String name, String id, String gender, int score1, int score2, int score3, int credit1, int credit2, int credit3) {
this.name = name;
this.id = id;
this.gender = gender;
this.score1 = score1;
this.score2 = score2;
this.score3 = score3;
this.credit1 = credit1;
this.credit2 = credit2;
this.credit3 = credit3;
}
public double getCreditProduct() {
return credit1 * credit2 * credit3;
}
@Override
public String toString() {
return name + " " + id + " " + gender + " " + getCreditProduct();
}
}
```
该程序先定义了一个学生类 `Student`,其中包含了学生的基本信息和成绩信息,以及计算学分积的方法 `getCreditProduct()`。在 `Main` 类中,创建一个学生数组并初始化,然后使用 `Arrays.sort()` 方法对学生数组排序,排序的依据是学生的学分积大小。最后输出排序后的结果。
阅读全文