2014-04-14 38 views
0

得到以下錯誤:「.Exception線程‘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); 
     } 

這編譯罰款,但我得到一個‘例外’(不知道是什麼那些還沒有)。

我看不出什麼問題,至少在這裏沒有。如果這被認爲是這種情況,我會添加更多的代碼。

回答

1

您的數組已經初始化爲包含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)的變量。

1

當您創建一個對象數組時,您所得到的只是一個正確大小但滿量程爲null的數組。您需要通過說new Account()並將其分配給數組來創建每個對象。你甚至可以在同一個循環中完成它。

1

您需要實例化一個Account,假設你有一個空的構造Account你會使用這樣的事情 -

for (int i=0;i<10;i++) { 
    AccArray[i] = new Account(); // <-- like so. 
    AccArray[i].setId(i); // this line is specified in the error 
    AccArray[i].setBalance(100); 
} 

此外,你應該嘗試並遵循Java的命名約定......所以也許更多的東西像,

Account[] accounts = new Account[10]; 

for (int i=0;i<10;i++) { 
    accounts[i] = new Account(); // <-- like so. 
    accounts[i].setId(i); // this line is specified in the error 
    accounts[i].setBalance(100); 
} 
0

正如其他人所指出的那樣,創造Account一個新的數組實際上並不產生任何Accounts;你必須自己動手new。爪哇8給你一個很好的方法來做到這一點:

Account[] accounts = new Account[10]; 
Arrays.setAll(accounts, i -> new Account()); 

的第二個參數setAll是λ表達式,它接受一個整數參數i(該元件爲一組的索引),並且將數組元素到new Account()。該表達式實際上並不使用索引,但是您可以使用表達式(或塊),如果需要,可以使用i

相關問題