java编写记账本系统
时间: 2023-09-13 08:10:52 浏览: 47
下面是一个简单的 Java 记账本系统的示例代码,可以作为参考:
```java
import java.util.ArrayList;
import java.util.Scanner;
public class AccountBookSystem {
private ArrayList<Account> accounts; // 记录账目
public AccountBookSystem() {
accounts = new ArrayList<>();
}
// 添加账目
public void addAccount(Account account) {
accounts.add(account);
}
// 显示所有账目
public void showAccounts() {
System.out.println("所有账目:");
for (Account account : accounts) {
System.out.println(account.toString());
}
}
// 查询账目
public void queryAccount(String type) {
System.out.println("查询结果:");
for (Account account : accounts) {
if (account.getType().equals(type)) {
System.out.println(account.toString());
}
}
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
AccountBookSystem accountBook = new AccountBookSystem();
while (true) {
System.out.println("请选择操作:1.添加账目 2.显示所有账目 3.按类型查询 4.退出");
int choice = scanner.nextInt();
switch (choice) {
case 1:
System.out.println("请输入账目类型:");
String type = scanner.next();
System.out.println("请输入账目金额:");
double amount = scanner.nextDouble();
System.out.println("请输入账目描述:");
String description = scanner.next();
Account account = new Account(type, amount, description);
accountBook.addAccount(account);
System.out.println("添加成功!");
break;
case 2:
accountBook.showAccounts();
break;
case 3:
System.out.println("请输入要查询的账目类型:");
type = scanner.next();
accountBook.queryAccount(type);
break;
case 4:
System.out.println("退出程序!");
return;
default:
System.out.println("输入错误,请重新选择操作!");
}
}
}
}
class Account {
private String type; // 账目类型
private double amount; // 账目金额
private String description; // 账目描述
public Account(String type, double amount, String description) {
this.type = type;
this.amount = amount;
this.description = description;
}
public String getType() {
return type;
}
public double getAmount() {
return amount;
}
public String getDescription() {
return description;
}
public String toString() {
return "类型:" + type + ",金额:" + amount + ",描述:" + description;
}
}
```
运行程序后,根据提示进行操作即可。可以添加账目、显示所有账目、按类型查询账目。账目信息通过 `Account` 类保存,每个账目包括类型、金额和描述。