模拟银行存取款业务java
时间: 2024-12-07 18:09:43 浏览: 36
模拟银行存取款业务在Java中通常涉及设计一个简单的银行账户类(BankAccount)和相关的操作类(如DepositService、WithdrawalService等),以及一些基本的用户管理。以下是简化的步骤和代码示例:
1. 定义BankAccount类:
```java
public class BankAccount {
private String accountNumber;
private double balance;
public BankAccount(String accountNumber, double initialBalance) {
this.accountNumber = accountNumber;
this.balance = initialBalance;
}
// 存款方法
public void deposit(double amount) {
if (amount > 0) {
balance += amount;
}
}
// 取款方法
public boolean withdraw(double amount) {
if (amount > 0 && amount <= balance) {
balance -= amount;
return true;
} else {
return false; // 资金不足或尝试取款金额大于当前余额
}
}
// 获取余额
public double getBalance() {
return balance;
}
// 其他可能的方法,如查询交易记录等
}
```
2. 创建服务类(Services):
```java
public class DepositService {
public void performDeposit(BankAccount account, double amount) {
account.deposit(amount);
System.out.println("存款成功,账户余额:" + account.getBalance());
}
}
public class WithdrawalService {
public boolean performWithdrawal(BankAccount account, double amount) {
return account.withdraw(amount);
}
}
```
3. 用户界面(User Interface):
```java
public class BankApp {
public static void main(String[] args) {
BankAccount customerAccount = new BankAccount("123456", 1000.00);
DepositService depositService = new DepositService();
WithdrawalService withdrawalService = new WithdrawalService();
// 存款示例
depositService.performDeposit(customerAccount, 500);
// 取款示例
boolean success = withdrawalService.performWithdrawal(customerAccount, 200);
if (success) {
System.out.println("取款成功");
} else {
System.out.println("取款失败");
}
// 查看余额
System.out.println("当前余额:" + customerAccount.getBalance());
}
}
```
阅读全文