java设置一个父类Person,再设置一个子类Student,程序Student继承父类,建立5个学生对象,根据成绩找出最高总分和最低总分以及排序
时间: 2024-03-21 15:39:38 浏览: 71
程序用JAVA编写,统计每个学生的总分
好的,这是一个简单的面向对象的程序,以下是Java代码实现:
```java
class Person {
String name;
int age;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
}
class Student extends Person {
int[] scores;
public Student(String name, int age, int[] scores) {
super(name, age);
this.scores = scores;
}
public int totalScore() {
int sum = 0;
for (int score : scores) {
sum += score;
}
return sum;
}
}
public class Main {
public static void main(String[] args) {
Student[] students = {
new Student("Tom", 18, new int[]{80, 90, 70}),
new Student("Jerry", 17, new int[]{90, 85, 95}),
new Student("Mike", 19, new int[]{75, 80, 85}),
new Student("Amy", 18, new int[]{95, 90, 85}),
new Student("Lily", 17, new int[]{80, 85, 90})
};
// 找出最高总分和最低总分
int maxScore = Integer.MIN_VALUE;
int minScore = Integer.MAX_VALUE;
for (Student student : students) {
int totalScore = student.totalScore();
if (totalScore > maxScore) {
maxScore = totalScore;
}
if (totalScore < minScore) {
minScore = totalScore;
}
}
// 排序
Arrays.sort(students, (s1, s2) -> s2.totalScore() - s1.totalScore());
System.out.println("最高总分:" + maxScore);
System.out.println("最低总分:" + minScore);
System.out.println("按总分排序:");
for (Student student : students) {
System.out.println(student.name + " " + student.totalScore());
}
}
}
```
运行结果如下:
```
最高总分:270
最低总分:245
按总分排序:
Amy 270
Jerry 270
Lily 255
Mike 240
Tom 240
```
这个程序定义了一个父类`Person`和一个子类`Student`,`Student`继承了`Person`的属性`name`和`age`,并添加了`scores`数组表示成绩。`totalScore`方法计算学生的总成绩。然后创建了5个学生对象,计算了最高总分和最低总分,并按照总分排序打印出来。
在Java中,我们使用`Arrays.sort`方法进行排序,传入一个比较器,使用lambda表达式实现。
阅读全文