orchlon Batsaikhan
orchlon Batsaikhan

Reputation: 111

Having problems declaring arrays of arrays of object Java

I have a problem using arrays of arrays of objects or simply arrays of objects and I'm pretty sure this isn't related to slick. Whenever the init method runs and get to the block part i'm getting a null pointer exception. I'm also sure that the problem is in me not declaring the Block objects properly. Please i really need some help on this.

import org.newdawn.slick.*;
import org.newdawn.slick.state.*;

public class Stages extends BasicGameState {
    LevelInfo level = new LevelInfo(1);
    Block block[][];
    public Stages(int state) {

    }
    public void init(GameContainer gc, StateBasedGame sbg) throws SlickException {
        level.init();
        for(int i = 0; i < 13;i++) {
            for(int j = 0; j < 13;j++) {
                block[i][j] = new Block(level.type[i][j]);
            }
        }

    }
    public void render(GameContainer gc, StateBasedGame sbg,Graphics g) throws SlickException {
        for(int i = 0; i < 13;i++) {
            for(int j = 0; j < 13;j++) {
                g.drawImage(block[i][j].image,j*60,i*60);
            }
        }
    }
    public void update(GameContainer gc, StateBasedGame sbg,int delta) throws SlickException {

    }
    public int getID() {
        return 2;
    }
}

Upvotes: 0

Views: 258

Answers (2)

Reimeus
Reimeus

Reputation: 159754

You never instantiate your 2D block array, resulting in the NPE then you attempt to assign the variable here

block[i][j] = new Block(level.type[i][j]);

You could declare your array thus:

private Block block[][] = new Block[13][13];

Upvotes: 1

Jon Skeet
Jon Skeet

Reputation: 1500355

You're never initializing block itself - it will always have a value of null. You need:

block = new Block[13][13];

in your init method, or in the constructor, or at the variable declaration.

A couple of other notes:

  • You should almost certainly make your variables private
  • You should probably avoid hard-coding the number 13 quite so often... could you have constants of WIDTH and HEIGHT perhaps?
  • It would be more idiomatic to declare the variable as:

    private Block[][] block;
    

    That keeps all the type information about the variable together. The "array part after the variable name" was really there to make existing C/C++ programmers happy when Java was introduced.

Upvotes: 3

Related Questions