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

Java课程作业计算问题:numCredits*creditFee+addFee始终返回0.0

嘿,我一眼就瞅出问题所在了——你的余额(balance)从始至终都没被正确初始化,还有几个小细节的逻辑漏洞,咱们一步步搞定:

1. 核心问题:Balance从未被赋值

你定义了numCredits * creditFee + addFee这个计算逻辑,但从来没把结果赋值给balance字段!

在你的Registration带参构造方法里,只给firstName、lastName、numCredits、addFee做了赋值,完全没管balance。默认情况下balance是0.0,所以输出自然一直是0。

修复方法:

在带参构造方法里添加一行代码,初始化balance:

public Registration(String firstName, String lastName, double numCredits, double addFee){
    this.firstName = firstName;
    this.lastName = lastName;
    this.numCredits = numCredits;
    this.addFee = addFee;
    // 新增:初始化余额
    this.balance = numCredits * creditFee + addFee;
}

2. 隐藏bug:setcreditFee方法逻辑错误

你现在的setcreditFee方法不管传入什么参数,都硬把creditFee设为70,这完全违背了setter的设计初衷:

public void setcreditFee(double creditFee){
    this.creditFee = 70; // 这里应该用传入的参数!
}

修复方法:

改成用传入的参数赋值:

public void setcreditFee(double creditFee){
    this.creditFee = creditFee;
}

3. addCredit/subCredit方法的逻辑优化

目前这两个方法的判断条件(balance > 0)不合理,而且没有同步更新numCredits字段:

  • 比如用户刚注册balance是正确的,想加学分,结果因为balance>0才允许?这逻辑没问题,但你没更新numCredits,后续获取学分数量还是旧的。
  • 减学分的时候应该先判断学分够不够减,而不是看balance。

优化后的代码:

public void addCredit(double addCredit){
    this.numCredits += addCredit; // 先更新学分数量
    this.balance += addCredit * creditFee; // 再更新余额
}

public void subCredit(double subCredit){
    // 确保学分不会减到负数
    if (this.numCredits >= subCredit) {
        this.numCredits -= subCredit;
        this.balance -= subCredit * creditFee;
    }
}

修复后的测试效果

当你运行RegistrationTester时,student1的余额会是15*70 +60 = 1110.0,student2的是12*70+45=885.0,输出就正常了!

等你解决完这个问题,后续要实现加减3学分的功能,直接调用student1.addCredit(3)和student1.subCredit(3)就行~

内容的提问来源于stack exchange,提问作者Dené Sphynx Logan

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.09 12:42:35