gpt4 book ai didi

java - 在java中初始化自定义类的二维数组

转载 作者:太空宇宙 更新时间:2023-11-04 06:39:19 24 4
gpt4 key购买 nike

当我尝试实例化包含二维接口(interface)数组的类时,出现 NullPointerException。在另一个类中,我有一个CompetitionGround类型的对象,我尝试做这样的事情来初始化它:

CompetitionGround groud;
ground=new CompetitionGround(5);

我的 ComparisonGround 类的构造函数如下所示:

public CompetitionGround(int boundries) {
for (int i = 0; i <boundries; i++)
for (int j = 0; j <boundries; j++)
eggs[i][j]=new Egg();
}

全类是:

public class CompetitionGround {

private IEgg eggs[][];

public void goIn(Rabbit rabbit) {
IPozition temp = rabbit.getPozition();
rabbit.Collect(eggs[temp.getPozitionX()][temp.getPozitionY()]);
}

public CompetitionGround(int boundries) {
for (int i = 0; i < boundries; i++)
for (int j = 0; j < boundries; j++)
eggs[i][j] = new Egg();
}

public void AddEgg(int x, int y, int points) {
eggs[x][y] = new Egg(points);
}
}

实现 IEgg 的 Egg 类有两种类型的构造函数。我尝试了两者并遇到了同样的问题。我究竟做错了什么?我想不通。

最佳答案

数组本身从未初始化,因此您还不能为其元素分配任何内容。在 2 个嵌套 for 循环中初始化之前,首先创建 2D 数组本身。

public CompetitionGround(int boundries  /* [sic] */) {
// Init array here.
eggs = new IEgg[boundries][boundries];

// You should use proper indenting.
for (int i = 0; i < boundries; i++)
for (int j = 0; j < boundries; j++)
eggs[i][j] = new Egg();
}

关于java - 在java中初始化自定义类的二维数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24894946/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com