用java编写一个程序,实现银行活期储蓄储户开户、销户、存入、支出活动,系统设计要求:(1)能比较迅速地找到储户的帐户,以实现存款、取款记账; (2)能比较简单,迅速地实现插入和删除,以实现开户和销户的需要。
时间: 2024-11-04 07:16:12 浏览: 7
C语言活期储蓄账目管理系统
在Java中,我们可以创建一个`BankAccount`类来模拟这个银行活期储蓄系统的储户账户。为了满足上述需求,我们可以采用数据结构如HashMap(键值对存储,查找快速),其中键为储户的ID,值为账户对象。以下是简单的示例代码:
```java
import java.util.HashMap;
class BankAccount {
private String accountId;
private double balance;
// 构造函数,开户并初始化余额为0
public BankAccount(String accountId) {
this.accountId = accountId;
this.balance = 0;
}
// 存款方法
public void deposit(double amount) {
if (amount > 0) {
balance += amount;
System.out.println("Deposit successful. New balance is " + balance);
} else {
System.out.println("Invalid deposit amount.");
}
}
// 支出方法
public boolean withdraw(double amount) {
if (amount <= balance) {
balance -= amount;
System.out.println("Withdrawal successful. New balance is " + balance);
return true;
} else {
System.out.println("Insufficient funds.");
return false;
}
}
// 销户方法,将余额转移至其他账户或注销
public void closeAccount() {
System.out.println("Closing account. Balance remaining: " + balance);
// 这里可以添加实际的操作,比如转账或清零
}
}
// 主程序
public class BankSystem {
private static HashMap<String, BankAccount> accounts = new HashMap<>();
public static void main(String[] args) {
// 开户
openAccount("123456");
// 存款和支取
depositAndWithdraw("123456", 1000, 800);
// 销户
closeAccount("123456");
}
// 插入新账户
public static void openAccount(String accountId) {
if (!accounts.containsKey(accountId)) {
accounts.put(accountId, new BankAccount(accountId));
System.out.println("Account opened successfully.");
} else {
System.out.println("Account already exists.");
}
}
// 存款和支取通用方法
public static void depositAndWithdraw(String accountId, double depositAmount, double withdrawalAmount) {
if (accounts.containsKey(accountId)) {
BankAccount account = accounts.get(accountId);
account.deposit(depositAmount);
if (account.withdraw(withdrawalAmount)) {
System.out.println("Transaction completed.");
}
} else {
System.out.println("Account not found.");
}
}
// 删除账户(仅作为示例,实际应用中需考虑资金转移等操作)
public static void closeAccount(String accountId) {
if (accounts.containsKey(accountId)) {
accounts.remove(accountId);
System.out.println("Account closed.");
} else {
System.out.println("Account does not exist.");
}
}
}
```
阅读全文