用java实现声明银行账户类Account,成员变量包括账号、储户姓名、开户时间、身份证号码、存 款余额等账户信息,成员方法包括开户、存款、取款、查询(余额、明细)、销户等操 作
时间: 2023-10-26 11:05:35 浏览: 108
以下是用Java实现的银行账户类Account:
```java
import java.util.ArrayList;
import java.util.Date;
public class Account {
private String accountNumber; // 账号
private String accountName; // 储户姓名
private Date openDate; // 开户时间
private String idNumber; // 身份证号码
private double balance; // 存款余额
private ArrayList<String> transactions; // 交易明细
// 构造函数
public Account(String accountNumber, String accountName, Date openDate, String idNumber, double balance) {
this.accountNumber = accountNumber;
this.accountName = accountName;
this.openDate = openDate;
this.idNumber = idNumber;
this.balance = balance;
this.transactions = new ArrayList<>();
}
// 开户
public void openAccount() {
System.out.println("开户成功!");
}
// 存款
public void deposit(double amount) {
this.balance += amount;
String transaction = String.format("存款:%.2f元,余额:%.2f元,时间:%s", amount, this.balance, new Date());
this.transactions.add(transaction);
System.out.println("存款成功!");
}
// 取款
public void withdraw(double amount) {
if (amount > this.balance) {
System.out.println("余额不足,取款失败!");
} else {
this.balance -= amount;
String transaction = String.format("取款:%.2f元,余额:%.2f元,时间:%s", amount, this.balance, new Date());
this.transactions.add(transaction);
System.out.println("取款成功!");
}
}
// 查询余额
public void checkBalance() {
System.out.println(String.format("余额:%.2f元", this.balance));
}
// 查询交易明细
public void checkTransactions() {
if (this.transactions.size() == 0) {
System.out.println("暂无交易明细!");
} else {
System.out.println("交易明细:");
for (String transaction : this.transactions) {
System.out.println(transaction);
}
}
}
// 销户
public void closeAccount() {
System.out.println("销户成功!");
}
}
```
然后,我们可以编写一个测试类来测试以上实现:
```java
import java.util.Date;
public class AccountTest {
public static void main(String[] args) {
Account account = new Account("1234567890", "张三", new Date(), "123456789012345678", 1000);
account.openAccount();
account.deposit(500);
account.checkBalance();
account.withdraw(200);
account.checkTransactions();
account.closeAccount();
}
}
```
以上测试类将输出以下结果:
```
开户成功!
存款成功!
余额:1500.00元
取款成功!
交易明细:
存款:500.00元,余额:1500.00元,时间:Mon Jun 28 22:26:34 CST 2021
取款:200.00元,余额:1300.00元,时间:Mon Jun 28 22:26:34 CST 2021
销户成功!
```
阅读全文