You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何为成绩册模型的Assignment类实现符合规则的accrueScore mutator方法?

解决方案

以下是实现了所有要求的accrueScore方法代码,完整类如下:

public class Assignment {
    // instance variables
    private String name;
    private int totalPoints;
    private int minScore;
    private int maxScore;
    private int sum;
    private int count;

    // Constructor for objects of class Assignment.
    public Assignment(String inName, int inTotalPoints) {
        // initialise instance variables
        this.name = inName;
        this.totalPoints = inTotalPoints;
        this.minScore = 0;
        this.maxScore = 0;
        this.sum = 0;
        this.count = 0;
    }

    // mutator method to update score fields
    public int accrueScore(int newScore) {
        // 规则1:校验分数范围,无效则直接返回当前计数
        if (newScore < 0 || newScore > totalPoints) {
            return count;
        }

        // 规则2:首个录入的分数,初始化min和max
        if (count == 0) {
            minScore = newScore;
            maxScore = newScore;
        } else {
            // 规则3:更新最高分
            if (newScore > maxScore) {
                maxScore = newScore;
            }
            // 规则4:更新最低分
            if (newScore < minScore) {
                minScore = newScore;
            }
        }

        // 规则5:累加分数到总和
        sum += newScore;
        // 规则6:更新录入计数
        count++;

        // 返回更新后的计数,可根据需求调整返回值(比如是否录入成功)
        return count;
    }
}

代码说明

  • 规则1实现:通过if (newScore < 0 || newScore > totalPoints)判断分数是否在有效范围,不符合则直接返回当前count,不执行后续操作。
  • 规则2实现:检查count是否为0(表示还未录入过分数),如果是则将minScore和maxScore都设为当前分数。
  • 规则3、4实现:非首次录入时,分别判断新分数是否高于当前最高分、低于当前最低分,符合条件则更新对应字段。
  • 规则5、6实现:只要分数有效,无论是否是首次录入,都将分数累加到sum,并将count加1。

内容的提问来源于stack exchange,提问作者Amber Lyda

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.28 20:13:08