优化一下,顾客数量也可以自定义
时间: 2024-03-21 22:44:35 浏览: 45
ECSHOP虚拟销量可自定义数量
好的,以下是优化后的程序:
```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();
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the number of customers: ");
int numCustomers = scanner.nextInt();
Customer[] customers = new Customer[numCustomers];
for (int i = 0; i < numCustomers; i++) {
System.out.print("Enter the name of customer " + (i + 1) + ": ");
String name = scanner.next();
System.out.print("Enter the number of transfers for customer " + (i + 1) + ": ");
int numTransfers = scanner.nextInt();
double[] amounts = new double[numTransfers];
int[] frequencies = new int[numTransfers];
for (int j = 0; j < numTransfers; j++) {
System.out.print("Enter the amount for transfer " + (j + 1) + " for customer " + (i + 1) + ": ");
amounts[j] = scanner.nextDouble();
frequencies[j] = 1;
}
customers[i] = new Customer(name, amounts, frequencies, 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);
}
}
```
和之前的程序相比,这个程序增加了一个 `Scanner` 对象,用于从用户输入中读取顾客数量和汇款信息。在 `main()` 方法中,先读取顾客数量,然后循环读取每个顾客的姓名、汇款次数和汇款金额,并创建对应的 `Customer` 对象。
这个程序可以自定义顾客数量和每个顾客的汇款金额和次数,并且能够模拟多个顾客并发汇款的场景。
阅读全文