I writing an application where i use an array within a class. This array is declared globally outside of any method scope so that all of the objects methods will be able to access the data. However, when i assign an object to a index that object is only available as a part of the array in that particular method. Any other method trying to read that index of the array gets a nullpointerexception.
Some code illustrating my usage:
Account[] accounts = new Account[8000];
public void addAccount() {
cli.printMessage("Welcome to the account add wizard.");
String holdername = cli.getInput(entername);
int accountnr = Integer.parseInt(cli.getInput(enternr));
BigDecimal accbalance = new BigDecimal(cli.getInput(enterinitialbalance));
accounts[accountnr] = new Account(holdername, accountnr, accbalance);
String accountinfo=accounts[accountnr].number + " " + " " + accounts[accountnr].holder + " " + accounts[accountnr].balance;
cli.printMessage(accountinfo);
}
Adding the account works all the way, this do not when ran from the same instance of this class:
public void getAccountinfo() {
int accountnr = Integer.parseInt(cli.getInput(getinfo));
String accountinfo=accounts[accountnr].number + "" + "" + accounts[accountnr].holder + accounts[accountnr].balance;
cli.printMessage(accountinfo);
}
Is this due to scope or is it due to me confusing instance and class variables? Might it be something completely different?
The error i get is a nullpointer exception at
String accountinfo=accounts[accountnr].number + "" + "" + accounts[accountnr].holder + accounts[accountnr].balance;
Grateful for any help!
In
getAccountInfoyou let the user input a number X.If the array ‘cell’ at X was not previously set via
addAccount,accounts[X]isnulland thusaccounts[X].numbercorrectly bombs out.