账目统计功能通过定义Record类存储收支记录,使用ArrayList集中管理,遍历数据计算总收入、支出与余额,并支持按月筛选统计,实现清晰的控制台输出。

实现一个控制台版本的Java个人记账软件,核心在于清晰的数据结构设计和合理的功能划分。账目统计功能是其中的重要模块,用于帮助用户了解收入、支出及结余情况。下面介绍如何一步步实现该功能。
1. 定义账目数据模型
要进行统计,先要定义好账目的基本结构。每个账目记录应包含时间、类型(收入/支出)、金额和备注。
public class Record { private String date; // 记录日期,如 "2024-05-20" private String type; // 类型:"收入" 或 "支出" private double amount; // 金额 private String description; // 备注public Record(String date, String type, double amount, String description) { this.date = date; this.type = type; this.amount = amount; this.description = description;}// Getter 方法public String getType() { return type; }public double getAmount() { return amount; }public String getDate() { return date; }
}
2. 存储与读取账目记录
使用 ArrayList 来存储所有账目记录,便于后续遍历统计。
立即学习“Java免费学习笔记(深入)”;
import java.util.ArrayList;import java.util.List;public class AccountBook {private List records;
public AccountBook() { records = new ArrayList();}public void addRecord(Record record) { records.add(record);}
}
3. 实现账目统计功能
统计功能主要包括:总收入、总支出、当前余额,也可按月份或类型进一步细分。
绘蛙AI修图
绘蛙平台AI修图工具,支持手脚修复、商品重绘、AI扩图、AI换色
285 查看详情
public void showStatistics() { double totalIncome = 0; double totalExpense = 0;for (Record record : records) { if ("收入".equals(record.getType())) { totalIncome += record.getAmount(); } else if ("支出".equals(record.getType())) { totalExpense += record.getAmount(); }}double balance = totalIncome - totalExpense;System.out.println("=== 账目统计 ===");System.out.printf("总收入: %.2f 元\n", totalIncome);System.out.printf("总支出: %.2f 元\n", totalExpense);System.out.printf("当前余额: %.2f 元\n", balance);
}
4. 扩展:按月份统计
若希望查看某个月的收支情况,可增加按月份筛选的功能。
public void showMonthlyStatistics(String month) { // month 格式如 "2024-05" double income = 0, expense = 0;for (Record record : records) { if (record.getDate().startsWith(month)) { if ("收入".equals(record.getType())) { income += record.getAmount(); } else { expense += record.getAmount(); } }}System.out.printf("=== %s 月统计 ===\n", month);System.out.printf("收入: %.2f 元\n", income);System.out.printf("支出: %.2f 元\n", expense);System.out.printf("结余: %.2f 元\n", income - expense);
}
在主程序中调用这些方法即可输出统计结果。例如:
AccountBook book = new AccountBook();book.addRecord(new Record("2024-05-01", "收入", 5000.0, "工资"));book.addRecord(new Record("2024-05-03", "支出", 800.0, "房租"));book.addRecord(new Record("2024-05-05", "支出", 200.0, "餐饮"));book.showStatistics(); // 显示总体统计book.showMonthlyStatistics("2024-05"); // 显示5月统计
基本上就这些。通过简单的类设计和循环统计,就能实现一个实用的控制台记账统计功能。后续可加入文件持久化(如保存到txt或CSV)来避免每次重启丢失数据。
以上就是Java制作个人记账软件_控制台版本的账目统计功能实现的详细内容,更多请关注创想鸟其它相关文章!
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 chuangxiangniao@163.com 举报,一经查实,本站将立刻删除。
发布者:程序猿,转转请注明出处:https://www.chuangxiangniao.com/p/1081672.html
微信扫一扫
支付宝扫一扫