初始化2D对象数组时出现空指针exception

我正在尝试制作2D平铺游戏,当制作包含贴图的数组时,我得到一个NullPointerException,这里有一些代码。 对不起,如果这是格式不好,第一个计时器

公共课世界{

//holds data for where to place images and rectangles int[][] worldDat = new int[25][25]; //hold rectangles for checking interaction with player Rectangle[][] blocks = new Rectangle[25][25]; //holds block's images to be painted Image[][] blockImage = new Image[25][25]; //holds position to be pained on screen int[][] location = new int[25][25]; //enumeration holding block's images and other things of the sort EWorldBlocks eBlocks; //sets all of the arrays listed above public void setupAll(){ for(int i = 0; i < 24; i++){ for(int e = 0; e < 24; e++){ blocks[i][e].setBounds(e * 20, i * 20, 20, 20); blocks[i][e].setLocation(e*20, i*20); if(worldDat[i][e] == 6){ blockImage[i][e] = getRandomGrass(); }else if(worldDat[i][e] == 0){ blockImage[i][e] = null; }else{ blockImage[i][e] = eBlocks.intToImage(worldDat[i][e]); } } } } //used to get a random block private Image getRandomGrass() { Random rand = new Random(); int r = rand.nextInt(2); r++; return eBlocks.intToImage(r); } public World(int[][] worldDat) { this.worldDat = worldDat; } } 

然后在这个类中调用(我相信它的一部分问题)

公共类worldDraw {

 //ALSO if there is a better way to do this, do tell levels levels = new levels(); static levels sLevels = new levels(); World level1; static World sLevel1 = new World(sLevels.getLevel1()); //called in paint method for panel public void draw(Graphics2D g2){ sLevel1.setupAll(); for(int i = 0; i < 24; i++){ for(int e = 0; i < 24; i++){ g2.drawImage(level1.blockImage[i][e], e*25, i*25, null); } } } //holds levels public worldDraw() { level1 = new World(levels.getLevel1()); } } 

创建对象数组时,您正在创建引用数组,但您没有分配引用。 在尝试使用它们之前,您必须先执行此操作。 可以认为它类似于创建一个鸡蛋盒。 在您首先用鸡蛋填充纸箱之前,您不能使用任何鸡蛋。 因此,例如你的块数组,首先需要将Rectangle对象分配给数组中的每个项目,然后才能调用它们上的方法。 这通常在for循环中完成。 例如,

 for(int i = 0; i < 24; i++){ for(int e = 0; e < 24; e++){ blocks[i][e] = new Rectangle(....); //... blocks[i][e].setBounds(e * 20, i * 20, 20, 20); blocks[i][e].setLocation(e*20, i*20); 

你需要知道Java不像C.

当你这样做:

 Rectangle[][] blocks = new Rectangle[25][25]; 

在您调用new并为其提供引用之前,块2D数组中的所有引用都为null。

所以你必须这样做:

 for(int i = 0; i < 24; i++){ for(int e = 0; e < 24; e++){ blocks[i][e] = new Rectangle(); // I don't know what arguments it takes. blocks[i][e].setBounds(e * 20, i * 20, 20, 20); blocks[i][e].setLocation(e*20, i*20);