Java Object数组java.lang.NullPointerException [英] Java Object array java.lang.NullPointerException
本文介绍了Java Object数组java.lang.NullPointerException的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我遇到了一个问题,我创建了一个对象数组,但是当我尝试解决某些问题时,我得到了一个 java.lang.NullPointerException
。
I am having a problem where I create an array of objects but I get a java.lang.NullPointerException
when i try to address something to it.
这是有问题的类。
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;
}
}
如果需要,请告诉我提供更多信息/代码
please let me know if i need to provide more info/code
推荐答案
这样做
public class Blocks {
public static Block[] b = new Block[8];
static {
// Instantiating the objects present in the array
for(int i=0; i<b.length; i++)
b[i] = new Block();
}
public Blocks() throws IOException {
// Now you can access them
new Air (b[0]);
new Stone(b[1]);
new Grass(b[2]);
new Dirt (b[3]);
}
您忘记实例化数组中的对象。所以它提示空指针异常
You forgot to instantiate the objects present in the array. So it is prompting null pointer exception
这篇关于Java Object数组java.lang.NullPointerException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文