java模拟银行账户管理系统
时间: 2023-10-17 11:34:59 浏览: 169
好的,我可以为您提供一个简单的Java模拟银行账户管理系统的示例。
首先,我们需要定义一个账户类,包括账户名、账户余额等属性和相关的方法,如存款、取款等。
```java
public class Account {
private String name;
private double balance;
public Account(String name, double balance) {
this.name = name;
this.balance = balance;
}
public String getName() {
return name;
}
public double getBalance() {
return balance;
}
public void deposit(double amount) {
balance += amount;
}
public void withdraw(double amount) {
if (amount <= balance) {
balance -= amount;
} else {
System.out.println("余额不足!");
}
}
}
```
接下来,我们可以定义一个银行类,包含多个账户和相关的操作方法,如开户、销户、查询余额等。
```java
import java.util.ArrayList;
public class Bank {
private ArrayList<Account> accounts;
public Bank() {
accounts = new ArrayList<>();
}
public void addAccount(Account account) {
accounts.add(account);
}
public void removeAccount(Account account) {
accounts.remove(account);
}
public double getBalance(String name) {
for (Account account : accounts) {
if (account.getName().equals(name)) {
return account.getBalance();
}
}
System.out.println("账户不存在!");
return -1;
}
public void deposit(String name, double amount) {
for (Account account : accounts) {
if (account.getName().equals(name)) {
account.deposit(amount);
System.out.println("存款成功!");
return;
}
}
System.out.println("账户不存在!");
}
public void withdraw(String name, double amount) {
for (Account account : accounts) {
if (account.getName().equals(name)) {
account.withdraw(amount);
System.out.println("取款成功!");
return;
}
}
System.out.println("账户不存在!");
}
}
```
最后,我们可以编写一个测试类,模拟用户使用银行账户管理系统的过程。
```java
import java.util.Scanner;
public class TestBank {
public static void main(String[] args) {
Bank bank = new Bank();
// 开户
Account account1 = new Account("张三", 1000);
Account account2 = new Account("李四", 2000);
bank.addAccount(account1);
bank.addAccount(account2);
Scanner scanner = new Scanner(System.in);
while (true) {
System.out.println("请选择操作:1.查询余额 2.存款 3.取款 4.退出");
int option = scanner.nextInt();
if (option == 1) {
System.out.println("请输入账户名:");
String name = scanner.next();
double balance = bank.getBalance(name);
if (balance >= 0) {
System.out.println("余额为:" + balance);
}
} else if (option == 2) {
System.out.println("请输入账户名和存款金额:");
String name = scanner.next();
double amount = scanner.nextDouble();
bank.deposit(name, amount);
} else if (option == 3) {
System.out.println("请输入账户名和取款金额:");
String name = scanner.next();
double amount = scanner.nextDouble();
bank.withdraw(name, amount);
} else if (option == 4) {
break;
} else {
System.out.println("输入错误,请重新选择!");
}
}
}
}
```
以上就是一个简单的Java模拟银行账户管理系统的示例,您可以参考并根据自己的需求进行修改和扩展。
阅读全文