2013-02-24 26 views
0

我是新來的Java和我在處理對象數組時遇到了問題。我的主要程序是這樣的:NullPointerException當創建OBJECT ARRAYS和使用它們

package bicycledemo; 

class BicycleDemo { 
    public static void main(String[] args) { 

     // Create two different 
     // Bicycle objects with an array 
     Bicycle[] bike = new Bicycle[2]; 

     bike[0].cadence=50; //line 10, where the NullPointerException prompts out 
     bike[0].gear=2; 

     bike[1].cadence=10; 
     bike[1].gear=3; 

     System.out.println("gear: "+bike[0].gear+"\n"+"cadence: "+bike[0].cadence+"\n"); 
     System.out.println("gear: "+bike[1].gear+"\n"+"cadence: "+bike[1].cadence+"\n"); 


     System.out.println("\b"); 
    } 
} 

和自行車類是這個:

package bicycledemo; 

public class Bicycle { 
    public Bicycle() { 

    } 

    public int cadence; 
    public int gear; 

} 

當我運行該程序,輸出錯誤是:

Exception in thread "main" java.lang.NullPointerException 
     at bicycledemo.BicycleDemo.main(BicycleDemo.java:10) 
Java Result: 1 

我想,發生什麼事是對象自行車沒有正確創建,但我不明白爲什麼。

非常感謝您的幫助!我非常渴望解決這個問題!

+0

@TedHopp:不,代碼真的*看起來沒什麼問題。 – 2013-02-24 18:27:21

回答

2

你從來沒有初始化你的數組元素,因此作爲你的數組元素是一個對象,它們被初始化爲默認值null。因此,當您嘗試在索引處調用元素時,它會拋出NPE

Bicycle[] bike = new Bicycle[2];// initializes the array with size 2 
             but the elements hold default 
             values(null in this case) 
    bike[0] = new Bicycle();// initializing the array element at index 0 
    bike[1] = new Bicycle();// initializing the array element at index 1 

當然更好的設計也有2 ARGS自行車的構造和it.or初始化屬性有setter和干將爲您的屬性。

public Bicycle(int cadence, int gear){ 
     this.cadence = cadence; 
     this.gear = gear; 
    } 

然後,

 bike[0] = new Bicycle(2, 2); 
     bike[1] = new Bicycle(3, 5); 
+0

非常感謝!我非常困惑,因爲我正在與C++進行比較,但這並沒有發生,所以我看不到答案! – davidws 2013-02-24 23:38:40

+0

@davidws歡迎您.. :)請標記這裏的答案之一爲接受。 :) – PermGenError 2013-02-24 23:42:46

2

您需要先填寫您的數組:

Bicycle[] bike = new Bicycle[2]; 
bike[0] = new Bicycle(); 
bike[1] = new Bicycle(); 

否則,您創建只包含null元素的數組。

4

這條線:

Bicycle[] bike = new Bicycle[2]; 

創建一個數組。它有兩個元素,並且這兩個元素最初都是空引用。您尚未創建任何Bicycle對象。然後在下一個語句中:

bike[0].cadence=50; 

......你試圖取消引用空值。您需要初始化數組元素在使用之前作爲對象:

// Set the first element of the array to refer to a newly created object 
bike[0] = new Bicycle(); 
// Then this will be fine 
bike[0].cadence = 50; 

如果你不明白究竟這是怎麼回事,它是你更加緊密地研究它的真的重要。瞭解參考和對象之間的區別(並且瞭解變量和數組只有包含引用或原始值,從未對象)是Java的基礎。在你「得到」之前,你會遇到各種困難。

注意,你也可以改變你的Bicycle類包括構造以節奏和齒輪的參數:

public Bicycle(int cadence, int gear) { 
    this.cadence = cadence; 
    this.gear = gear; 
} 

然後你可以改變你的初始化爲:

bike[0] = new Bicycle(50, 2); 
bike[1] = new Bicycle(10, 3); 

甚至爲陣列創建的一部分:

Bicycle[] bike = { 
    new Bicycle(50, 2), 
    new Bicycle(10, 3) 
}; 
+0

非常感謝!我非常困惑,因爲我正在與C++進行比較,但這並沒有發生,所以我看不到答案! – davidws 2013-02-24 23:36:48

2

你必須se將數組中的每個索引都添加到新實例,然後才能開始訪問其屬性。

Bicycle[] bike = new Bicycle[2]; 

bike[0] = new Bicycle(); // add this 

bike[0].cadence=50; 
... 
0

您創建了一個對象數組,並且無需初始化即可訪問它們。

bike = [null, null] - your result 
相關問題