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));
}
}