Java 6-1 计算成绩 (15分)
体操比赛计算选手成绩的办法是去掉一个最高分和最低分后再计算平均分,而学校考察一个班级的某科目的考试情况时,是计算全班同学的平均成绩。体操Gymnastics类和学校School类都实现了ComputerAverage接口,但是实现的方式不同。
接口方法定义:
ComputerAverage接口有 如下方法:
public double average(double x[]);
其中 x 是用户传入的参数。 函数须返回平均值。
裁判测试程序样例:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
double a[] ;
double b[];
Scanner sc=new Scanner(System.in);
String str1=sc.nextLine();
String[] str_a=str1.split(" ");
a=new double[str_a.length];
for(int i=0;i<str_a.length;i++)
a[i]=Double.parseDouble(str_a[i]);
String str2=sc.nextLine();
String[] str_b=str2.split(" ");
b=new double[str_b.length];
for(int i=0;i<str_b.length;i++)
b[i]=Double.parseDouble(str_b[i]);
CompurerAverage computer;
computer=new Gymnastics();
double result=computer.average(a); //computer调用average(double x[])方法,将数组a传递给参数x
//System.out.printf("%n");
System.out.printf("体操选手最后得分:%5.3f\n",result);
computer=new School();
result=computer.average(b); //computer调用average(double x[])方法,将数组b传递给参数x
System.out.printf("班级考试平均分数:%-5.2f",result);
}
}
/* 请在这里填写答案 */
//定义接口
//定义Gymnastics 类实现接口
//定义School类实现接口
输入样例:
9.89 9.88 9.99 9.12 9.69 9.76 8.97
89 56 78 90 100 77 56 45 36 79 98
输出样例:
体操选手最后得分:9.668
班级考试平均分数:73.09
我的答案
import java.util.*;
public class Main
{
public static void main(String[] args)
{
double a[];
double b[];
Scanner sc=new Scanner(System.in);
String str1=sc.nextLine();//接收第一行数据
String []str_a=str1.split(" ");//利用split分割数据,使用str_a数组存储
a=new double[str_a.length];
for(int i=0;i<str_a.length;i++)
{
a[i]=Double.parseDouble(str_a[i]);//parse方法把字符转换为double
}
String str2=sc.nextLine();
String []str_b=str2.split(" ");
b=new double[str_b.length];
for(int i=0;i<str_b.length;i++)
{
b[i]=Double.parseDouble(str_b[i]);
}
CompurerAverage c;
c=new Gymnastics();
double result;
result=c.average(a);//computer调用average(double x[])方法,将数组a传递给参数x
System.out.printf("体操选手最后得分:%5.3f\n",result);
c=new School();
result=c.average(b); //computer调用average(double x[])方法,将数组b传递给参数x
System.out.printf("班级考试平均分数:%-5.2f",result);
}
}
interface CompurerAverage
{
double average(double x[]);
}
class Gymnastics implements CompurerAverage
{
public double average(double x[])
{
double sum=0;
Arrays.sort(x);//Arrays.sort方法排序
//也可自己写排序方法
//也可遍历找出最大最小值
for(int i=1;i<x.length-1;i++)
{
sum+=x[i];
}
return sum/(x.length-2);
}
}
class School implements CompurerAverage
{
public double average(double x[])
{
double sum=0;
for(int i=0;i<x.length;i++)
{
sum += x[i];
}
double result=sum/(x.length);
return result;
}
}
还没有评论,来说两句吧...