17370845950

如何实现一个 Money 类的加法方法

本文介绍了如何在 Java 的 `Money` 类中实现一个 `add` 方法,该方法接受另一个 `Money` 对象作为参数,并将该对象的值加到当前对象上。重点在于处理美分和美元之间的进位,确保美分值始终在 0 到 99 之间。同时,也考虑了输入参数为空的情况,并返回修改后的当前对象。

在开发涉及货币计算的应用程序时,创建一个 Money 类来表示金额是很常见的做法。一个关键的功能是能够将两个 Money 对象相加。以下是如何在 Java 中实现 Money 类的 add 方法,该方法将另一个 Money 对象的值添加到当前对象,并正确处理美分和美元之间的进位。

首先,我们来看一下 Money 类的基本结构(基于你提供的代码):

class Money {
    private int cents;
    private int dollars;

    public Money() {
        this.cents = 0;
        this.dollars = 0; // 初始化美元为0
    }

    public Money(Scanner sc) {
        String token = sc.next();
        int dot = token.indexOf(".");
        this.cents = Integer.parseInt(token.substring(dot + 1));
        this.dollars = Integer.parseInt(token.substring(1, dot));
    }

    public String toString() {
        return "$" + dollars + "." + (cents < 10 ? "0" : "") + cents; // 格式化输出,确保美分始终显示两位
    }

    public boolean equals(Money other) {
        if (!(other instanceof Money)) {
            return false;
        }
        return this.dollars == other.dollars && this.cents == other.cents;
    }

    // add 方法将在这里实现
}

现在,我们来实现 add 方法。该方法需要考虑以下几点:

  1. 空值检查: 检查传入的 other 对象是否为空。如果是,则不进行任何操作。
  2. 美分相加: 将 other 对象的 cents 值加到当前对象的 cents 值上。
  3. 进位处理: 如果相加后的 cents 值大于等于 100,则需要进行进位。将 cents 值除以 100 的余数作为新的 cents 值,并将 dollars 值加 1。
  4. 美元相加: 将 other 对象的 dollars 值加到当前对象的 dollars 值上。
  5. 返回当前对象: 返回修改后的当前对象。

以下是 add 方法的实现:

public Money add(Money other) {
    if (other != null) {
        this.cents += other.cents;
        this.dollars += other.dollars; // 先加美元,简化进位逻辑
        if (this.cents >= 100) {
            this.dollars += this.cents / 100; // 增加美元
            this.cents %= 100; // 取余数,保持cents在0-99之间
        }
    }
    return this;
}

完整代码示例:

import java.util.Scanner;

class Money {
    private int cents;
    private int dollars;

    public Money() {
        this.cents = 0;
        this.dollars = 0;
    }

    public Money(Scanner sc) {
        String token = sc.next();
        int dot = token.indexOf(".");
        this.cents = Integer.parseInt(token.substring(dot + 1));
        this.dollars = Integer.parseInt(token.substring(1, dot));
    }

    public String toString() {
        return "$" + dollars + "." + (cents < 10 ? "0" : "") + cents;
    }

    public boolean equals(Money other) {
        if (!(other instanceof Money)) {
            return false;
        }
        return this.dollars == other.dollars && this.cents == other.cents;
    }

    public Money add(Money other) {
        if (other != null) {
            this.cents += other.cents;
            this.dollars += other.dollars;
            if (this.cents >= 100) {
                this.dollars += this.cents / 100;
                this.cents %= 100;
            }
        }
        return this;
    }

    public static void main(String[] args) {
        Money m1 = new Money();
        m1.dollars = 5;
        m1.cents = 50;

        Money m2 = new Money();
        m2.dollars = 2;
        m2.cents = 75;

        m1.add(m2);

        System.out.println(m1); // 输出: $8.25
    }
}

注意事项:

  • 输入验证: 在实际应用中,应该对输入进行验证,例如确保美分值和美元值都是非负数。
  • 不可变性: 更好的设计方式是创建一个新的 Money 对象来表示结果,而不是修改当前对象。这样可以避免副作用,并使代码更易于理解和维护。 如果需要返回新的对象,则需要修改 add 方法,如下所示:
public Money add(Money other) {
    if (other == null) {
        return new Money(this.dollars, this.cents); // 返回当前对象的副本
    }

    int newCents = this.cents + other.cents;
    int newDollars = this.dollars + other.dollars;

    if (newCents >= 100) {
        newDollars += newCents / 100;
        newCents %= 100;
    }

    return new Money(newDollars, newCents); // 返回新的 Money 对象
}

// 辅助构造函数,方便创建新的Money对象
public Money(int dollars, int cents) {
    this.dollars = dollars;
    this.cents = cents;
}
  • 精度问题: 对于更复杂的货币计算,建议使用 BigDecimal 类来避免浮点数精度问题。

总结:

通过以上步骤,我们成功地为 Money 类实现了一个 add 方法,该方法能够正确地将两个 Money 对象相加,并处理美分和美元之间的进位。 根据实际需求,可以选择修改当前对象或者返回新的对象。 同时,也需要注意输入验证和精度问题,以确保代码的健壮性和准确性。