gpt4 book ai didi

java - 将 Account 对象添加到 ArrayList

转载 作者:行者123 更新时间:2023-12-01 19:03:09 28 4
gpt4 key购买 nike

public class Bank {
private ArrayList<Account> accounts;
private int numberOfAccounts;

public Bank() {
numberOfAccounts = 0;
accounts = new ArrayList<Account>();
}

public int getNumOfAccounts() {
return numberOfAccounts;
}

public void addAccount(Account a) {
numberOfAccounts++;
accounts.add(a);
}

public Account findAccount(int id) {
int index = id - 1;
if (accounts.size() >= id){
return accounts.get(index);
}
else return null;
}

public void addMonthlyInterest() {
for (Account x : accounts) {
x.addMonthlyInterest();
}
}

public void removeAccount(Account a) {
numberOfAccounts--;
accounts.remove(a);
}
}

因此,当我将帐户添加到 ArrayList,然后检查大小时,它一直告诉我其中没有任何内容。我使用 .add() 添加的方式有问题吗?

这是我的 BankTest 的一部分。我不太确定 testAddAccount 使用什么(JUnit 方面),但我知道它们没有被添加,因为当我尝试查找帐户时,它们都不存在。

import static org.junit.Assert.*;
import static org.junit.Assert.assertEquals;

import java.util.ArrayList;

import org.junit.Test;

public class BankTest {
private final ArrayList<Account> accounts = new ArrayList<Account>();
private Bank bank = new Bank();
private java.util.Random rand;
// private static final double[] RATES;
// private static final int[] TYPES;

SavingsAccount sa = new SavingsAccount(0.034);
CheckingAccount ca = new CheckingAccount(0.034, 100);
CreditCardAccount cca = new CreditCardAccount(0.034, 100);

@Test
public void testAddAccount() {
// Tests Bank.addAccount() by adding many random accounts to the bank.
// SavingsAccount sa = new SavingsAccount(0.034);
SavingsAccount sa = new SavingsAccount(0.034);
CheckingAccount ca = new CheckingAccount(0.034, 100);
CreditCardAccount cca = new CreditCardAccount(0.034, 100);
bank.addAccount(sa);
bank.addAccount(ca);
bank.addAccount(cca);
if (accounts.size() == 3){
System.out.println("true");
}else System.out.println("false");

}

@Test
public void testFindAccount() {
// Tests Bank.findAccount() by finding all existing accounts and
// attempting to find some non-existing accounts.
bank.addAccount(sa);
bank.addAccount(ca);
bank.addAccount(cca);

int size = accounts.size();
System.out.println(size);
accounts.get(0);
assertEquals(sa, bank.findAccount(1));
assertEquals(ca, bank.findAccount(2));
assertEquals(cca, bank.findAccount(3));

assertNull(bank.findAccount(50));
assertNull(bank.findAccount(80));
assertNull(bank.findAccount(230));

}

}

最佳答案

我需要看看你如何实例化和使用 Bank 对象,但我猜这就是你的问题所在。每当您创建新银行时,帐户列表都会初始化 - 每当您尝试访问帐户列表时,您是否都会创建新银行?

关于java - 将 Account 对象添加到 ArrayList,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11388873/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com