首页 > Java > java教程 > 正文

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

心靈之曲
发布: 2025-11-16 19:03:15
原创
948人浏览过

如何实现一个 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 方法的实现:

法语写作助手
法语写作助手

法语助手旗下的AI智能写作平台,支持语法、拼写自动纠错,一键改写、润色你的法语作文。

法语写作助手 31
查看详情 法语写作助手
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 对象相加,并处理美分和美元之间的进位。 根据实际需求,可以选择修改当前对象或者返回新的对象。 同时,也需要注意输入验证和精度问题,以确保代码的健壮性和准确性。

以上就是如何实现一个 Money 类的加法方法的详细内容,更多请关注php中文网其它相关文章!

相关标签:
最佳 Windows 性能的顶级免费优化软件
最佳 Windows 性能的顶级免费优化软件

每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。

下载
来源:php中文网
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
最新问题
开源免费商场系统广告
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新 English
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号