[英]Null Pointer Exception on Array in Java
以下代码在 Java 中返回 NullPointerException。 谁能澄清我的错误?
public void deposit2()
{
BankAccounts[] accounts2 = new BankAccounts[10];
accounts2[3].deposit();
}
BankAccounts[] accounts2 = new BankAccounts[10];
是相同的
BankAccounts[] accounts2 = {null, null, null, ... null }; // (10 times)
您需要将值分配到的元素accounts2
(或者,至少要件3)试图取消引用它们之前。
只需在代码中声明它,然后使用 for 循环将对象引用分配给所有索引。
例如:
public void deposit2()
{
BankAccounts[] accounts2 = new BankAccounts[10];
for(int i=0;i<10;i++)
{
accounts2[i] = new BankAccounts();
}
accounts2[3].deposite();
}
BankAccounts[] accounts2 = new BankAccounts[10];
创建一个对象,即具有 10 个引用的银行帐户数组,可以指向 10 个 BankAccount 对象,它们被初始化为 null ,您需要创建实际的银行对象,试试这个
BankAccounts[] accounts2 = new BankAccounts[10];
for(BankAccounts b:accounts2)//for each loop
{
b=new BankAccounts();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.