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

Java OOP作业假期总费用计算结果恒为0的问题求助

问题根因

  • 你定义的season_num、discount两个int类型成员变量没有被正确赋值:setSeason()、setTypeDiscount()两个方法里才会给这两个变量赋值,但你在PriceCalculator构造方法中仅存储了传入的season、typeDiscount字符串参数,从未调用过这两个set方法。int类型成员变量的默认初始值为0,因此计算时pricePerDay * season_num * numberOfDays的结果必然为0。
  • 现有折扣计算逻辑不符合预期:你当前写的res-(res/discount)逻辑错误,以vip的20%折扣为例,该写法等价于仅减免原价的5%,和预期的减免20%不符。

修复步骤

1. 调整构造方法,触发set方法完成初始化

修改PriceCalculator类的构造方法,补充对两个set方法的调用:

PriceCalculator(String season, String typeDiscount, int numberOfDays, double pricePerDay){
    this.numberOfDays = numberOfDays;
    this.pricePerDay = pricePerDay;
    // 调用set方法完成season_num、discount的赋值
    setSeason(season);
    setTypeDiscount(typeDiscount);
}

2. 修正折扣计算逻辑

修改displayAccountInfo方法内的计算代码:

void displayAccountInfo() {
    double totalBeforeDiscount = pricePerDay * season_num * numberOfDays;
    // 按折扣比例计算实付金额:20%折扣即支付原价的80%
    result = totalBeforeDiscount * (100 - discount) / 100;
    System.out.println(result);
}

运行验证

按照你提供的测试参数summer、vip、5天、单日价格50.25,修复后计算结果为:
50.25 * 4 * 5 * 0.8 = 804.0,和预期输出一致。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.02 06:27:03