用java编译以下问题:假设某一银行账户,它可接受顾客的汇款,每做一次汇款,便可计算出汇款的总额。现有多个顾客,每人分多次将钱(每个顾客汇入的时间和钱数不一样)汇入到该银行账户。试编写一个程序,模拟实际作业,要求自定义每个顾客的汇款金额和次数,然后有系统随机安排汇款顺序,每个顾客汇完自己的次数后将不会再汇款,显示总金额
时间: 2024-03-21 09:44:34 浏览: 121
以下是用Java编写的程序:
```java
import java.util.*;
public class BankAccount {
private double totalAmount;
public BankAccount() {
totalAmount = 0;
}
public double getTotalAmount() {
return totalAmount;
}
public void addMoney(double amount) {
totalAmount += amount;
}
}
class Customer {
private String name;
private double[] amounts;
private int[] frequencies;
private BankAccount account;
public Customer(String name, double[] amounts, int[] frequencies, BankAccount account) {
this.name = name;
this.amounts = amounts;
this.frequencies = frequencies;
this.account = account;
}
public String getName() {
return name;
}
public void doTransfer() {
Random rand = new Random();
for (int i = 0; i < amounts.length; i++) {
if (frequencies[i] == 0) {
continue;
}
double amount = amounts[i];
account.addMoney(amount);
frequencies[i]--;
System.out.println(name + " transferred " + amount + " to bank account");
try {
Thread.sleep(rand.nextInt(1000) + 500);
}
catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
public class BankSimulation {
public static void main(String[] args) {
BankAccount account = new BankAccount();
Customer[] customers = new Customer[3];
customers[0] = new Customer("Alice", new double[]{100, 200, 300}, new int[]{3, 2, 1}, account);
customers[1] = new Customer("Bob", new double[]{50, 50, 50, 50, 50}, new int[]{5, 4, 3, 2, 1}, account);
customers[2] = new Customer("Charlie", new double[]{500, 200}, new int[]{2, 1}, account);
int totalTransfers = 0;
while (true) {
List<Customer> activeCustomers = new ArrayList<>();
for (Customer customer : customers) {
if (Arrays.stream(customer.frequencies).sum() > 0) {
activeCustomers.add(customer);
}
}
if (activeCustomers.size() == 0) {
break;
}
Collections.shuffle(activeCustomers);
for (Customer customer : activeCustomers) {
customer.doTransfer();
}
totalTransfers += activeCustomers.size();
}
System.out.println("Total amount transferred: " + account.getTotalAmount());
System.out.println("Total number of transfers: " + totalTransfers);
}
}
```
程序中定义了三个类 `BankAccount`、`Customer` 和 `BankSimulation`。
`BankAccount` 类表示银行账户,包含一个成员变量 `totalAmount` 表示汇款总额,和两个方法 `getTotalAmount()` 和 `addMoney()` 分别用于获取总金额和添加汇款金额。
`Customer` 类表示顾客,包含四个成员变量 `name`、`amounts`、`frequencies` 和 `account` 分别表示顾客姓名、汇款金额、汇款次数和银行账户。`doTransfer()` 方法用于执行汇款操作,随机选择一笔汇款并向银行账户汇款,直到该顾客所有的汇款次数都完成。
`BankSimulation` 类表示银行模拟程序,包含一个 `main()` 方法。首先创建一个银行账户和三个顾客,在一个无限循环中,每次随机选择一个顾客进行汇款,直到所有顾客的汇款次数都完成。循环结束后输出汇款总额和汇款次数。
这个程序可以自定义每个顾客的汇款金额和次数,并且能够模拟多个顾客并发汇款的场景。
阅读全文