java程序Student继承父类Person,建立5个学生对象,根据成绩找出最高总分和最低总分以及排序
时间: 2024-03-21 18:38:31 浏览: 53
好的,针对您的问题,我已经了解了您的需求。下面是解决方案:
首先,我们需要定义两个类:Person 和 Student,其中 Student 继承自 Person。
```java
public class Person {
private String name;
private int age;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
public class Student extends Person {
private int mathScore;
private int englishScore;
private int chineseScore;
public Student(String name, int age, int mathScore, int englishScore, int chineseScore) {
super(name, age);
this.mathScore = mathScore;
this.englishScore = englishScore;
this.chineseScore = chineseScore;
}
public int getMathScore() {
return mathScore;
}
public void setMathScore(int mathScore) {
this.mathScore = mathScore;
}
public int getEnglishScore() {
return englishScore;
}
public void setEnglishScore(int englishScore) {
this.englishScore = englishScore;
}
public int getChineseScore() {
return chineseScore;
}
public void setChineseScore(int chineseScore) {
this.chineseScore = chineseScore;
}
public int getTotalScore() {
return mathScore + englishScore + chineseScore;
}
}
```
然后,我们可以建立 5 个学生对象,并计算他们的总分。
```java
public static void main(String[] args) {
Student[] students = {
new Student("张三", 18, 80, 90, 70),
new Student("李四", 19, 85, 95, 80),
new Student("王五", 20, 90, 80, 75),
new Student("赵六", 21, 70, 75, 80),
new Student("钱七", 22, 95, 85, 90)
};
int maxTotalScore = Integer.MIN_VALUE;
int minTotalScore = Integer.MAX_VALUE;
for (Student student : students) {
int totalScore = student.getTotalScore();
if (totalScore > maxTotalScore) {
maxTotalScore = totalScore;
}
if (totalScore < minTotalScore) {
minTotalScore = totalScore;
}
}
System.out.println("最高总分:" + maxTotalScore);
System.out.println("最低总分:" + minTotalScore);
Arrays.sort(students, Comparator.comparingInt(Student::getTotalScore).reversed());
for (Student student : students) {
System.out.println(student.getName() + " " + student.getAge() + " " + student.getTotalScore());
}
}
```
以上就是解决方案,希望能对您有所帮助。
阅读全文