2012-03-18 101 views
1

所以我創建了一個名爲dicegame的類。這是構造函數。我創建的對象數組是怎樣的一組空值?

public class dicegame { 

private static int a,b,winner;

public dicegame() 
{ 
    a = 0; 
    b = 0; 
    winner = 2; 
} 

現在在主,我創建這個對象的數組(我把它叫做意大利麪條的樂趣)。

public static void main(String[] args) 
{ 
    dicegame[] spaghetti = new dicegame[10]; 
spaghetti[1].roll(); 


} 

但是,當我嘗試做任何事情的元素在數組中,我得到了NullPointerException異常。當我試圖打印其中一個元素時,我得到了一個null。

回答

1

您創建了一個數組,但必須爲該數組的每個元素指定一些內容(例如,新的dicegame())。

我的Java略有生疏,但是這應該是接近:

for (int i=0; i<10; i++) 
{ 
    spaghetti[i] = new dicegame(); 
} 
1

你需要spaghetti[1]=new dicegame()你就可以調用卷()前。
現在你正在分配一個數組,但是不要。在這個數組中放置任何對象,所以默認情況下java會將它們設爲null。

1
new dicegame[10] 

只是創建一個包含10個空元素的數組。您仍然必須在每個元素中添加一個骰子游戲:

spaghetti[0] = new dicegame(); 
spaghetti[1] = new dicegame(); 
spaghetti[2] = new dicegame(); 
... 
1

1.您剛剛聲明瞭數組變量,但尚未創建該對象。試試這個

2.你應該從零開始索引而不是一個索引。

dicegame[] spaghetti = new dicegame[10]; // created array variable of dicegame 

for (int i = 0; i < spaghetti.length; i++) { 
    spaghetti[i] = new dicegame(); // creating object an assgning to element of spaghetti 
    spaghetti[i].roll(); // calling roll method. 
} 
0

首先,你應該爲你的每個意大利麪條輸入創建對象。 你可以從任何你想要的值開始。只要確保數組的大小相應匹配,這樣就不會得到ArrayIndexOutOfBounds異常。因此,如果你想從1開始,並有10個類別的骰子游戲的對象,你將不得不指定數組的大小爲11(因爲它從零開始)。

你的主要功能應該是這樣的:

public static void main(String[] args) 
{ 
dicegame[] spaghetti = new dicegame[11]; 
//the below two lines create object for every spaghetti item 
for(int i=1;i<=11;i++) 
spaghetti[i]=new dicegame(); 

//and now if you want to call the function roll for the first element,just call it 
spaghetti[1].roll; 
}