我正在编写一个应用程序,我在类中使用了一个数组。这个数组在全局方法范围之外声明,以便所有的对象方法都能够访问数据。但是,当我将一个对象分配给索引时,该对象仅作为该特定方法中数组的一部分提供。试图读取该数组索引的任何其他方法都会得到一个nullpointerexception。Java数组和范围
一些代码说明我的用法:
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);
}
添加帐户工作一路,这不从这个类的同一实例中运行时:
public void getAccountinfo() {
int accountnr = Integer.parseInt(cli.getInput(getinfo));
String accountinfo=accounts[accountnr].number + "" + "" + accounts[accountnr].holder + accounts[accountnr].balance;
cli.printMessage(accountinfo);
}
这是由于范围还是由于我混淆了实例和类变量?可能是完全不同的东西?
错误我得到的是一个空指针异常在
String accountinfo=accounts[accountnr].number + "" + "" + accounts[accountnr].holder + accounts[accountnr].balance;
感谢您的帮助!
你预计会发生什么,实际发生了什么? – Jivings 2012-02-25 13:38:33
它应该没问题 - 请显示一个简短但完整的*程序来证明问题。 (您应该考虑使用camelCase作为您的变量名称,以便清晰起见。) – 2012-02-25 13:38:35
accountnr在getAccountinfo()中具有什么值 – 2012-02-25 13:39:58