I am new to java, I am trying to add an object to an array of objects. I have 2 Class, Bank and Account. Bank contains an array of Accounts objects.
Bank constructor initializes the Accounts array.
public Bank (String bankName, int num) {
nameOfBank = bankName;
max = num;
Account[] accounts = new Account[max];
count = 0;
This is my addAccount method.
public boolean addAccount (Account acct) {
if(acct == null) {
return false;
}
accounts[count++] = acct;
return true;
}
This is how I add the account in main
newBank.addAccount(test);
ps. I am not allowed to use anything other than java array.(no arrayList)
Exception in thread "main" java.lang.NullPointerException
at Bank.addAccount(Bank.java:55)
at TestBank.main(TestBank.java:15)
You've defined accounts
as a local variable to the constructor, not a class level member.
public class Bank {
Account[] accounts;
int count;
public Bank(String bankName, int num) {
accounts = new Account[num];
count = 0;
}
public boolean addAccount(Account acct) {
// Do your work
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.