Jonathon M
Jonathon M

Reputation: 71

2D Array of classes are null

Im working on a program that uses class Map that stores a 2D Array of Tile objects to form a grid. In the map class:

public class Map {
    private int x = 80;
    private int y = 40;
    //store the entire map - a 50x50 2d array
    private tile[][] grid = new tile[x][y];
    public void Map() {
        initialize();
        grid[0][0].tile('.');
    }

    public void initialize() {
        for (int i = 0; i < y; i++) {
            for (int j = 0; j < x; j++) {
                grid[j][i] = new tile();
            }
        }
    }
    public void display() {
        for (int i = 0; i < y-1; i++) {
            for (int j = 0; j < x-1; j++) {
                System.out.println("Pass [" + j + "][" + i + "]");
                System.out.print(grid[j][i].c());

            }
            System.out.println();
        }
    }
}

In the tile class:

public class tile {
    private String title = "null";
    private int id = 0;
    private char c = ' ';
    private boolean isVis = false;

    public tile() {
        id = 1;
        format(id);
    }

    private void format(int n) {
        c = 'A';
        title = "foo";
        isVis = false
    }

    public char c() { return c; }
}

When running the program, I get an output of:

Pass [0][0]
Exception in thread "main" java.lang.NullPointerException
    at Map.display(Map.java:22)
   at rogue.main(rogue.java:7)

highlighting the line:

System.out.print(grid[j][i].c());

What I think is happening is that the class inst being initialised once created. When I just print

System.out.print(grid[j][i]);

it returns a page full of "nullnullnull" What could I do to ensure the objects are initialised properly?

Upvotes: 1

Views: 84

Answers (1)

Eran
Eran

Reputation: 393986

public void Map()

is not a constructor (it's a regular method), so it's not invoked when you create a Map instance, and your initialize method is never called.

Change it to

public Map()

Upvotes: 4

Related Questions