无法调用包含class2对象数组的class1方法

时间:2017-08-06 14:02:21

标签: java arrays

我认为一些概念很清楚,但显然这并不完全正确。我确信这是非常简单的事情并且要求你回答而不是责怪我或标记为重复等,因为我搜索了其他类似的问题,但它们并不完全像我的。

所以我有这个简单的类 Bank ,它通过给出它的大小来创建一个对象数组 BankAccount 。 Bank类有方法isFull来检查数组是否已满,但是我不能从类MainApp中调用,我只是创建实例来测试我的方法。

银行

public class Bank {

    // array of BANKACCOUNT objects
    private BankAccount[] accountList;      // will hold all the accounts

    private int totalAccounts;              // to hold the total number of accounts

    public Bank(int sizeIn) {
        totalAccounts = sizeIn;
        accountList = new BankAccount[totalAccounts];
    }

    // check if the list is full
    public boolean isFull() {
        if(accountList.length == totalAccounts) {
           return true;
        }
        return false;
    }

    // add an item to the array
    public boolean add(BankAccount accountIn) {
        boolean added = false;
        if(isFull()){
            System.out.println("The account list is full");
            added = false;
        } else {
            accountList[totalAccounts] = accountIn;
            totalAccounts++;
            added = true;
        }
        return added;
    }
    // other methods...

的BankAccount

public class BankAccount {
    private String nameOfHolder;
    private String accNumber;
    private double balance;
    private static double interestRate; 

    public BankAccount(String INPname, double INPbalance){
        accNumber = "NL35FAKE" + Randomize.RandomNumGen(); //created a random number for every bank account in a separate class
        nameOfHolder = INPname;
        balance = INPbalance;
    }
    // other methods...

主程序

public class MainApp {
    Bank[] bankList = new Bank[3];
    BankAccount acc1 = new BankAccount("Stacey", 7500);
    BankAccount acc2 = new BankAccount("Maria", 15000);
    bankList[0].add(acc1);
    bankList[1].add(acc2);
    bankList.isFull();   // THIS DOES NOT WORK. 

除非我这样称呼,否则我看不到 isFull()方法:
bankList [0] .isFull()这没有任何意义,因为我想查看帐户的链接。

提前致谢。 :)

1 个答案:

答案 0 :(得分:2)

你做错了,

你正在创建Bank数组,你只需要一个, 然后您可以将BankAccount添加到该银行。并检查isFull()

public class MainApp {
    public static void main(String args[]){
        Bank bank = new Bank(3);// a bank that will hold up to 3 accounts
        BankAccount acc1 = new BankAccount("Stacey", 7500);
        BankAccount acc2 = new BankAccount("Maria", 15000);
        bank.add(acc1);
        bank.add(acc2);
        bank.isFull();
    }
}