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

实现一个控制台版本的Java个人记账软件,核心在于清晰的数据结构设计和合理的功能划分。账目统计功能是其中的重要模块,用于帮助用户了解收入、支出及结余情况。下面介绍如何一步步实现该功能。
要进行统计,先要定义好账目的基本结构。每个账目记录应包含时间、类型(收入/支出)、金额和备注。
public class Record {
private String date; // 记录日期,如 "2024-05-20"
private String type; // 类型:"收入" 或 "支出"
private double amount; // 金额
private String description; // 备注
<pre class='brush:java;toolbar:false;'>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; }}
使用 ArrayList 来存储所有账目记录,便于后续遍历统计。
立即学习“Java免费学习笔记(深入)”;
import java.util.ArrayList;
import java.util.List;
<p>public class AccountBook {
private List<Record> records;</p><pre class='brush:java;toolbar:false;'>public AccountBook() {
records = new ArrayList<>();
}
public void addRecord(Record record) {
records.add(record);
}}
统计功能主要包括:总收入、总支出、当前余额,也可按月份或类型进一步细分。
public void showStatistics() {
double totalIncome = 0;
double totalExpense = 0;
<pre class='brush:java;toolbar:false;'>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);}
若希望查看某个月的收支情况,可增加按月份筛选的功能。
public void showMonthlyStatistics(String month) {
// month 格式如 "2024-05"
double income = 0, expense = 0;
<pre class='brush:java;toolbar:false;'>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, "餐饮"));
<p>book.showStatistics(); // 显示总体统计
book.showMonthlyStatistics("2024-05"); // 显示5月统计</p>基本上就这些。通过简单的类设计和循环统计,就能实现一个实用的控制台记账统计功能。后续可加入文件持久化(如保存到txt或CSV)来避免每次重启丢失数据。
以上就是Java制作个人记账软件_控制台版本的账目统计功能实现的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号