如何实现Money类的add方法:将另一对象的值加到当前对象?
实现Money类的add方法解决方案
你的add方法核心需要处理美分相加后的进位逻辑——因为100美分等于1美元,必须确保cents字段最终值不超过99。以下是两种符合需求的实现方案:
方案1:修改当前对象并返回自身
这种实现直接把传入的Money对象金额加到当前对象中,完全匹配你“将该对象的金额值加到当前对象中”的需求:
public Money add(Money other) { // 计算两个对象的美分总和 int totalCents = this.cents + other.cents; // 计算需要进位到美元的数量 int carryOver = totalCents / 100; // 更新当前对象的美分:取模100得到剩余的美分数 this.cents = totalCents % 100; // 更新当前对象的美元:加上对方的美元数和美分进位的数量 this.dollars += other.dollars + carryOver; // 返回修改后的当前对象 return this; }
方案2:创建新对象返回(保持原对象不变)
如果希望当前对象的状态不被修改,而是返回一个新的Money对象存储相加结果,可以用这种实现(建议补充一个接收美元和美分的构造函数,让代码更规范):
// 先给Money类新增一个构造函数(可选,但更规范) public Money(int dollars, int cents) { this.dollars = dollars; // 提前处理传入美分可能超过99的情况,避免后续问题 this.dollars += cents / 100; this.cents = cents % 100; } // 实现add方法 public Money add(Money other) { int totalCents = this.cents + other.cents; int totalDollars = this.dollars + other.dollars + totalCents / 100; int remainingCents = totalCents % 100; return new Money(totalDollars, remainingCents); }
关键注意点
- 必须处理进位:比如
$5.99 + $3.02的情况,美分总和是101,需要进位1美元,最终结果是$9.01,上述两种方案都能正确处理这类边界场景。 - 原代码中的无参构造函数只初始化了
cents为0,dollars默认是0,所以方案1可以直接使用现有构造逻辑。
内容的提问来源于stack exchange,提问作者szymonf
相关产品推荐
相关产品推荐

