用java编译以下问题:假设某一银行账户,它可接受顾客的汇款,每做一次汇款,便可计算出汇款的总额。现有多个顾客,每人分多次将钱(每个顾客汇入的时间和钱数不一样)汇入到该银行账户。试编写一个程序,模拟实际作业,要求自定义顾客数量、每个顾客的汇款金额和次数,不同顾客汇款次数和金额不同,同一个顾客每次汇款金额相同,然后有系统随机安排汇款顺序,每个顾客汇完自己的次数后将不会再汇款,显示总金额
时间: 2024-03-22 19:36:54 浏览: 29
用java多线程做的银行汇款问题
4星 · 用户满意度95%
好的,下面是Java代码实现:
```java
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Random;
public class BankAccountSimulation {
private int numOfCustomers;
private List<Customer> customers;
private double totalAmount;
public BankAccountSimulation(int numOfCustomers) {
this.numOfCustomers = numOfCustomers;
this.customers = new ArrayList<>();
this.totalAmount = 0;
initializeCustomers();
}
private void initializeCustomers() {
Random rand = new Random();
for (int i = 1; i <= numOfCustomers; i++) {
int numOfTimes = rand.nextInt(5) + 1; //每个顾客汇款次数随机生成1-5次
double amount = rand.nextDouble() * 10000; //每个顾客汇款金额随机生成0-10000元
Customer c = new Customer(i, numOfTimes, amount);
customers.add(c);
}
}
public void simulate() {
while (true) {
// 所有顾客都汇完款,则结束
if (customers.stream().allMatch(Customer::isFinished)) {
break;
}
// 随机选择一个还没汇完款的顾客进行汇款
Collections.shuffle(customers);
for (Customer c : customers) {
if (!c.isFinished()) {
c.makeTransfer();
totalAmount += c.getAmount();
break;
}
}
}
System.out.println("所有顾客汇款完成,总金额为:" + totalAmount);
}
public static void main(String[] args) {
BankAccountSimulation simulation = new BankAccountSimulation(10);
simulation.simulate();
}
}
class Customer {
private int id;
private int numOfTimes;
private double amount;
private int times;
public Customer(int id, int numOfTimes, double amount) {
this.id = id;
this.numOfTimes = numOfTimes;
this.amount = amount;
this.times = 0;
}
public boolean isFinished() {
return times == numOfTimes;
}
public double getAmount() {
return amount;
}
public void makeTransfer() {
times++;
System.out.println("顾客" + id + "第" + times + "次汇款" + amount + "元");
}
}
```
以上代码实现了一个简单的银行账户汇款模拟系统。其中,我们通过 `BankAccountSimulation` 类来控制整个系统的运行。在初始化时,我们随机生成了一些顾客,每个顾客的汇款次数和金额也都是随机的。在 `simulate` 方法中,我们随机选择一个还没汇完款的顾客进行汇款,直到所有顾客都汇完款为止。在每次汇款后,我们更新了总金额,并输出了当前顾客的汇款信息。最终,当所有顾客都汇完款后,我们输出了总金额。
阅读全文