2012-03-18 104 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; 
}