|
发表于 2023-10-29 17:56:41
|
显示全部楼层
根据题目描述,可以设计以下类图:
- +-------------------+
- | StaffRecruit |
- +-------------------+
- | |
- | - scores: double[] |
- | |
- | + average(): double|
- | + max(): double |
- | + min(): double |
- +-------------------+
- ^
- |
- |
- +-------------------+
- | FinalExam |
- +-------------------+
- | |
- | - scores: double[] |
- | |
- | + average(): double|
- | + max(): double |
- | + min(): double |
- +-------------------+
复制代码
在类图中, StaffRecruit 和 FinalExam 都实现了 IAverage 接口,该接口定义了 average(double[] x) 抽象方法和 max(double[] x) 、 min(double[] x) 默认方法。
下面是相应的代码实现:
- interface IAverage {
- double average(double[] x);
- default double max(double[] x) {
- double max = Double.MIN_VALUE;
- for (double score : x) {
- if (score > max) {
- max = score;
- }
- }
- return max;
- }
- default double min(double[] x) {
- double min = Double.MAX_VALUE;
- for (double score : x) {
- if (score < min) {
- min = score;
- }
- }
- return min;
- }
- }
- class StaffRecruit implements IAverage {
- private double[] scores;
- public StaffRecruit(double[] scores) {
- this.scores = scores;
- }
- @Override
- public double average(double[] x) {
- // 去掉一个最高分和最低分
- double sum = 0;
- double min = min(x);
- double max = max(x);
- for (double score : x) {
- if (score != min && score != max) {
- sum += score;
- }
- }
- return sum / (x.length - 2);
- }
- }
- class FinalExam implements IAverage {
- private double[] scores;
- public FinalExam(double[] scores) {
- this.scores = scores;
- }
- @Override
- public double average(double[] x) {
- double sum = 0;
- for (double score : x) {
- sum += score;
- }
- return sum / x.length;
- }
- }
- public class Main {
- public static void main(String[] args) {
- double[] staffRecruitScores = { 80, 90, 95, 85, 88, 92, 87 };
- double[] finalExamScores = { 75, 85, 90, 92, 88, 82, 80, 85, 90, 95, 85, 88, 92, 87, 85, 90, 95, 85, 88, 92 };
- StaffRecruit staffRecruit = new StaffRecruit(staffRecruitScores);
- FinalExam finalExam = new FinalExam(finalExamScores);
- System.out.println("Staff Recruit Average: " + staffRecruit.average(staffRecruitScores));
- System.out.println("Final Exam Average: " + finalExam.average(finalExamScores));
- }
- }
复制代码
在测试应用程序中,我们创建了一个 StaffRecruit 对象和一个 FinalExam 对象,并传入相应的成绩数组。然后,调用 average() 方法分别计算了工作人员招聘面试成绩的平均分和期末考试成绩的平均分,并将结果打印出来。
注意:为了简化代码,我们直接将成绩数组作为参数传递给 average() 方法,实际应用中可能需要通过类的成员变量来传递。 |
|