用Java编写,设置一个父类,再设置一个子类 Person Student id name sex double []score; 程序Student继承父类,建立5个学生对象,根据成绩找出最高总分和最低总分以及排序
时间: 2024-03-20 18:45:14 浏览: 122
可以按照以下方式设置父类和子类:
```java
// 父类
public class Person {
protected String id;
protected String name;
protected String sex;
public Person(String id, String name, String sex) {
this.id = id;
this.name = name;
this.sex = sex;
}
}
// 子类
public class Student extends Person {
private double[] score;
public Student(String id, String name, String sex, double[] score) {
super(id, name, sex);
this.score = score;
}
public double getTotalScore() {
double total = 0.0;
for (double s : score) {
total += s;
}
return total;
}
}
```
在子类中新增了一个 double 类型的数组 score,以及一个计算总分的方法 getTotalScore()。
接下来可以在主函数中创建 5 个学生对象,并对它们的成绩进行操作:
```java
public static void main(String[] args) {
Student[] students = new Student[5];
students[0] = new Student("001", "张三", "男", new double[]{85, 90, 95});
students[1] = new Student("002", "李四", "女", new double[]{80, 85, 90});
students[2] = new Student("003", "王五", "男", new double[]{75, 80, 85});
students[3] = new Student("004", "赵六", "女", new double[]{70, 75, 80});
students[4] = new Student("005", "钱七", "男", new double[]{65, 70, 75});
double maxTotal = Double.MIN_VALUE;
double minTotal = Double.MAX_VALUE;
// 计算最高总分和最低总分
for (Student s : students) {
double total = s.getTotalScore();
if (total > maxTotal) {
maxTotal = total;
}
if (total < minTotal) {
minTotal = total;
}
}
System.out.println("最高总分:" + maxTotal);
System.out.println("最低总分:" + minTotal);
// 对学生进行排序
Arrays.sort(students, Comparator.comparingDouble(Student::getTotalScore).reversed());
// 输出排序后的学生信息
for (Student s : students) {
System.out.println(s.name + " 总分:" + s.getTotalScore());
}
}
```
在主函数中,首先创建了 5 个学生对象,并使用 getTotalScore() 方法计算了每个学生的总分。接着使用循环找出最高总分和最低总分,并输出结果。最后使用 Arrays.sort() 方法对学生对象进行排序,排序的依据是总分,排序方式为降序。最后输出排序后的学生信息。
阅读全文