体育比赛计算选手成绩的办法是去掉一个最高分和最低分后再计算平均分,而学校考查一个班级的某科目的考试情况时是计算全班同学的平均成绩。Gymnastics类和School类都实现了ComputerAverage接口,但实现的方式不同。 interface ComputerAverage{ public double average(double x[]); } 根据题意运用lamada表达式,分别给出Gymnastics类和School类的实现,并进行测试。
时间: 2024-02-18 20:04:14 浏览: 119
以下是Gymnastics类和School类的实现方式:
```java
public class Gymnastics implements ComputerAverage {
@Override
public double average(double[] x) {
double sum = 0;
double max = x[0];
double min = x[0];
for (double score : x) {
sum += score;
if (score > max) {
max = score;
}
if (score < min) {
min = score;
}
}
return (sum - max - min) / (x.length - 2);
}
}
public class School implements ComputerAverage {
@Override
public double average(double[] x) {
double sum = 0;
for (double score : x) {
sum += score;
}
return sum / x.length;
}
}
```
接下来是测试代码:
```java
public class Test {
public static void main(String[] args) {
Gymnastics gymnastics = new Gymnastics();
School school = new School();
double[] gymnasticsScores = {9.5, 9.8, 9.3, 9.6, 9.2};
double gymnasticsAverage = gymnastics.average(gymnasticsScores);
System.out.println("Gymnastics average: " + gymnasticsAverage);
double[] schoolScores = {80, 85, 90, 75, 95};
double schoolAverage = school.average(schoolScores);
System.out.println("School average: " + schoolAverage);
}
}
```
输出结果:
```
Gymnastics average: 9.433333333333334
School average: 85.0
```
注意:在实现Gymnastics类和School类时需要添加@Override注解,这是为了确保方法重写的正确性。
阅读全文