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



所以我正在创建一个名为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。

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

我的Java有点生疏,但这应该很接近:

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

只创建一个包含10个空元素的数组。你仍然需要在每个元素中加入一个骰子游戏:

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

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

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.
}

首先,您应该为您的每个意大利面条输入创建对象。你可以从你想要的任何价值开始。只需确保数组的大小相应匹配,这样就不会出现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;
} 

最新更新