体操比赛计算选手成绩的办法是去掉一个最高分和最低分,然后再计算平均分。而学校考查一个班级的某科目的考试情况时,是计算全班同学的平均成绩。
设计:
接口:ComputerAverage
方法: average方法。参数:double类型的数组;返回double类型的数值。
Gymnastics类[体操类]和School类[学校类]实现ComputerAverage接口的average方法。
主类MainClass中,
定义一个体操选手比赛分数的数组:
{9.21, 8.53, 8.65, 9.50, 9.88, 8.76, 9.46, 9.78},通过Gymnastics类的实例化对象,调用average方法,计算该体操选手的比赛得分。
定义一个班级科目的成绩的数组:
{80.5, 88, 98.5, 99, 78, 88 ,85 ,81.6, 92.5},通过School类的实例化对象,调用average方法,计算该班级科目的平均成绩。
package shiyan_10;
import java.text.*;
public class MainClass {
public static void main(String[] agrs) {
Gymnastics gymnastics = new Gymnastics();
School school = new School();
double tc[] = {9.21,8.53,8.65,9.50,9.88,8.76,9.46,9.78};
double bj[] = {80.5,88,98.5,99,78,88,85,81.6,92.5};
System.out.println("体操的平均分:"+ new DecimalFormat("0.00").format(gymnastics.average(tc)));
System.out.println("班级的平均分:"+ new DecimalFormat("0.00").format(school.average(bj)));
}
}
package shiyan_10;
public interface ComputerAverage {
double average(double[] a);
}
package shiyan_10;
public class Gymnastics implements ComputerAverage{//体操类
public double average(double[] a) {
double sum = 0;
double max = a[0];
double min = a[0];
for (int i = 0; i < a.length; i++) {
sum += a[i];
if (a[i]>max) {
max = a[i];
}
if (a[i]<min) {
min = a[i];
}
}
return (sum-max-min)/(a.length-2);
}
}
package shiyan_10;
public class School implements ComputerAverage {//学校类
public double average(double[] a) {
double sum = 0;
double max = a[0];
double min = a[0];
for (int i = 0; i < a.length; i++) {
sum += a[i];
if (a[i]>max) {
max = a[i];
}
if (a[i]<min) {
min = a[i];
}
}
return (sum)/(a.length);
}
}