体育比赛计算选手成绩的办法是去掉一个最高分和最低分后再计算平均分,而学校考查一个班级的某科目的考试情况时是计算全班同学的平均成绩。Gymnastics类和School类都实现了ComputerAverage接口,但实现的方式不同。 interface ComputerAverage{ public double average(double x[]); } 根据题意运用Lambda表达式,分别给出Gymnastics类和School类的实现,并进行测试。
时间: 2024-02-17 22:00:43 浏览: 134
下面是Gymnastics类和School类的实现方法以及测试代码:
```java
interface ComputerAverage{
public double average(double x[]);
}
public class Gymnastics {
public static void main(String[] args) {
double[] scores = {9.8, 9.5, 9.3, 9.9, 9.2};
ComputerAverage ca = (x) -> {
double sum = 0;
double min = x[0];
double max = x[0];
for (double score : x) {
if (score < min) {
min = score;
}
if (score > max) {
max = score;
}
sum += score;
}
return (sum - min - max) / (x.length - 2);
};
System.out.println("Gymnastics average score: " + ca.average(scores));
}
}
public class School {
public static void main(String[] args) {
double[] scores = {90, 75, 82, 93, 88};
ComputerAverage ca = (x) -> {
double sum = 0;
for (double score : x) {
sum += score;
}
return sum / x.length;
};
System.out.println("School average score: " + ca.average(scores));
}
}
```
在这个例子中,我们使用了Lambda表达式来实现ComputerAverage接口,分别计算了Gymnastics类和School类的平均分数。在Gymnastics类中,我们去掉了最高分和最低分,然后计算平均分数。在School类中,我们直接计算全班同学的平均分数。最后,我们分别调用两个类的main方法进行测试,并输出计算得到的平均分数。
阅读全文