请你提供一个完整的java程序,要求该程序定义一个Student数组,其中保存学生的基本信息:姓名,学号,性别,还有分别保存的3门课程成绩以及对应的学分,并计算这三门课程的学分积,按照学分积的降幂排序输出。
时间: 2024-10-12 19:08:37 浏览: 64
```java
import java.util.Arrays;
class Course {
String name;
double grade;
double credit;
public Course(String name, double grade, double credit) {
this.name = name;
this.grade = grade;
this.credit = credit;
}
public double getTotalCredit() {
return grade * credit;
}
}
class Student {
String name;
int id;
char gender;
Course[] courses = new Course[3];
public void addCourse(Course course) {
courses[courses.length - 1] = course;
}
@Override
public String toString() {
double totalCredit = 0;
for (Course course : courses) {
totalCredit += course.getTotalCredit();
}
Arrays.sort(courses, (a, b) -> Double.compare(b.getTotalCredit(), a.getTotalCredit()));
return "Name: " + name + ", ID: " + id + ", Gender: " + gender +
", Total Credit: " + totalCredit + ", Courses (Highest to Lowest): " + Arrays.toString(courses);
}
}
public class Main {
public static void main(String[] args) {
// 创建学生数组
Student[] students = new Student[2];
students[0] = new Student();
students[0].name = "张三";
students[0].id = 1001;
students[0].gender = 'M';
students[0].addCourse(new Course("数学", 85, 4));
students[0].addCourse(new Course("物理", 90, 3));
students[0].addCourse(new Course("英语", 88, 2));
students[1] = new Student();
students[1].name = "李四";
students[1].id = 1002;
students[1].gender = 'F';
students[1].addCourse(new Course("化学", 95, 4));
students[1].addCourse(new Course("生物", 87, 2));
students[1].addCourse(new Course("语文", 80, 3));
for (Student student : students) {
System.out.println(student);
}
}
}
```
这个Java程序首先定义了两个类,`Course`表示单门课程,包含名字、分数和学分;`Student`表示学生,包含姓名、学号、性别和一个课程数组。然后在`main`函数中创建了一个`Student`数组,并给每个学生添加了课程,最后通过`toString`方法按照总学分积降序排列并打印出每个学生的详细信息。
阅读全文