[英]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.