为什么我创建的对象数组是一组空值?

时间:2012-03-18 06:33:58

标签: java arrays null

所以我正在创建一个名为dicegame的类。这是构造函数。

public class dicegame {

private static int a,b,winner;

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

现在主要是,我正在创建一个这个对象的数组(我称之为spaghetti以获得乐趣)。

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


}

但是当我尝试对数组中的元素做任何事情时,我得到了NullPointerException。当我尝试打印其中一个元素时,我得到了一个null。

5 个答案:

答案 0 :(得分:1)

您创建了一个数组,但您必须为数组的每个元素分配一些内容(例如new dicegame())。

我的Java略显生锈,但这应该很接近:

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

答案 1 :(得分:1)

在您调用roll()之前,您需要spaghetti[1]=new dicegame() 现在你正在分配一个数组,但不是。将任何对象放在此数组中,因此默认情况下java将它们设为null。

答案 2 :(得分:1)

new dicegame[10]

只创建一个包含10个空元素的数组。你仍然需要在每个元素中添加一个dicegame:

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

答案 3 :(得分: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.
}

答案 4 :(得分:0)

首先,您应该为您的每个意大利面条输入创建对象。 你可以从你想要的任何价值开始。只需确保数组的大小相应匹配,这样就不会得到ArrayIndexOutOfBounds Exception。

所以,如果你想从1开始并拥有类dicegame的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;
}