用java语言写:对象数组 输入多个学生的学号,姓名,数学,语文,英语成绩,按总分从大到小排序。
时间: 2024-10-29 17:16:53 浏览: 7
在Java中,我们可以创建一个名为`Student`的对象类,包含学号、姓名以及各科成绩属性。然后,我们可以通过对象数组存储多个学生,并计算总分。这里是一个简单的示例:
首先,创建一个`Student`类:
```java
public class Student {
private int id;
private String name;
private double mathScore;
private double chineseScore;
private double englishScore;
public Student(int id, String name, double math, double chinese, double english) {
this.id = id;
this.name = name;
this.mathScore = math;
this.chineseScore = chinese;
this.englishScore = english;
}
// 计算总分
public double getTotalScore() {
return mathScore + chineseScore + englishScore;
}
// getters and setters (省略)
}
```
接着,创建并填充对象数组,按总分排序并输出:
```java
import java.util.Arrays;
public class Main {
public static void main(String[] args) {
// 创建学生对象数组
Student[] students = new Student[5];
students[0] = new Student(1, "张三", 90, 85, 95);
students[1] = new Student(2, "李四", 88, 92, 90);
students[2] = new Student(3, "王五", 92, 87, 92);
students[3] = new Student(4, "赵六", 95, 86, 90);
students[4] = new Student(5, "刘七", 89, 91, 93);
// 按总分排序
Arrays.sort(students, (s1, s2) -> s2.getTotalScore() - s1.getTotalScore());
// 输出排序后的学生信息
for (Student student : students) {
System.out.println("学号:" + student.getId() +
", 姓名:" + student.getName() +
", 总分:" + student.getTotalScore());
}
}
}
```
在这个例子中,我们使用了Java内置的`Arrays.sort`方法配合lambda表达式对数组进行了排序。
阅读全文