出现以下错误:“线程“main”中出现异常 java.lang.NullPointerException” ”
// Creates 10 accounts
Account[] AccArray = new Account[10];
// Data fields
double atmVal;
// Sets each account's discrete id and initial balance to 100
for (int i=0;i<10;i++){
AccArray[i].setId(i); // this line is specified in the error
AccArray[i].setBalance(100);
}
这编译得很好,但我得到了一个“异常(exception)”(还不确定那些是什么)。
我根本看不出有什么问题,至少这里没有。如果情况确实如此,我将添加更多代码。
最佳答案
您的数组已初始化为包含 10 个帐户,但它们仍然为空。将循环更改为:
for (int i=0;i<10;i++){
ArrArray[i] = new Account(); // whatever constructor parameters are needed
AccArray[i].setId(i); // this line is specified in the error
AccArray[i].setBalance(100);
}
话虽如此,我建议您使用小写名称命名变量(例如 accArray
)。
关于java - 我可以不这样做吗?收到 'exception' 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23050331/