Java对象数组java.lang.NullPointerException

我有一个问题,我创建一个对象数组但我得到一个java.lang.NullPointerException当我尝试解决它的问题。

这是有问题的class级。

 public class Blocks { public static Block[] b = new Block[8]; public Blocks() throws IOException { new Air (b[0]); new Stone(b[1]); new Grass(b[2]); new Dirt (b[3]); } 

这是类Block。

 public class Block { private Texture Texture = null; private int S = World.BLOCK_SIZE; private boolean hasTexture = true; private String texturePath = null; public void setTexture(String path) throws IOException { this.texturePath = path; Texture = TextureLoader.getTexture("PNG", new FileInputStream(new File(path))); } public void draw(int Xa, int Ya) { GL11.glTranslatef(Xa, Ya, 0); //GL11.glRotatef(0, 0, 1, 0); //GL11.glRotatef(0, 1, 0, 0); if(hasTexture) { Texture.bind(); GL11.glBegin(GL11.GL_QUADS); GL11.glColor3f(0.5f, 0.5f, 1); //GL11.glNormal3f(0, 0, 1); GL11.glTexCoord2f(0, 0); GL11.glVertex2f(0, 0); GL11.glTexCoord2f(0, 1); GL11.glVertex2f(0, S); GL11.glTexCoord2f(1, 1); GL11.glVertex2f(S, S); GL11.glTexCoord2f(1, 0); GL11.glVertex2f(S, 0); GL11.glEnd(); } } void hasTexture(boolean b) { this.hasTexture = b; } } 

如果我需要提供更多信息/代码,请告诉我

这样做吧

 public class Blocks { public static Block[] b = new Block[8]; static { // Instantiating the objects present in the array for(int i=0; i 

您忘记实例化数组中存在的对象。 所以它提示空指针exception

您似乎正在创建一个名为b的空数组,其中包含8个插槽(类型为块),然后使用对(空)数组的引用实例化对象(例如new Air (b[0]); )。

如果Air的构造函数无法处理可能是空指针exception源的null参数

首先尝试将一些对象放入b

对于初学者,你可以看看这个: –

 public static Block[] b = new Block[8]; public Blocks() throws IOException { new Air (b[0]); new Stone(b[1]); new Grass(b[2]); new Dirt (b[3]); } 

你没有实例化数组元素。 b[0], b[1], etc..仍然是null引用。