0

When I try to iterate through my 2D array of objects, I get a NullPointerException. I know that means the object I am trying to use is null, but I can't see why. I have 3 classes, Main, Map, and Tile. The array is a 2D array of tiles within the class Map. I then create a new Map called map1 in Main, and try to read some values from each tile with a for loop.

Main:

public class Main {
    public static void main(String[] args) {
        Map map1 = new Map(5, 6);
        map1.listTiles();
    }
}

Map:

public class Map {

    int width;
    int height;
    Tile[][] tiles;

    public Map(int Width, int Height) {
        width = Width;
        height = Height;
        tiles = new Tile[width][height];
    }

    public void listTiles() {
        for(Tile[] tileArray : tiles){
            for(Tile tile : tileArray) {
                System.out.println(tile.tileType);
            }
        }
    }
}

Tile:

public class Tile {
    public String tileType = "Grass";
    public int xCoord = 0;
    public int yCoord = 0;
}

As it turns out, replacing System.out.println(tile.tileType); with System.out.println(tile); results in null being written to the console 30 times. I still don't know why though.

  • 1
    When System.out.println(tile.tileType); is executed, it's giving the NullPointerException, since always 'title' object is null. Because you haven't added Title objects to the array. – Geeth Lochana Apr 30 '16 at 09:31

1 Answers1

1

Thats because you didn't create any Tile objects and for sure, you didn't placed them in array. So, you need first to create objects, put them in array, and then you will be able to print them out (assuming you created valid toString() method, when you print just tile).

For example:

 public Map(int Width, int Height) {
        width = Width;
        height = Height;
        tiles = new Tile[width][height];
        for (int i = 0; i < width; i++) {
             for (int j = 0; j < width; j++) {
                  tiles[i][j] = new Tile();
             }
        }
    }

But again, it would be best if you would create specific method to new Tile place in (i,j) position where you provide all needed variables for Tile (do you want xCoord and yCoord related to i and j or?).

Adnan Isajbegovic
  • 2,057
  • 13
  • 25
  • That solved the problem, thanks. But if I try to use ` for(Tile[] tileArray : tiles){ for(Tile tile : tileArray) { tile = new Tile(); } }` then it doesn't work. Any idea why? – ToshibaAbhorsen Apr 30 '16 at 10:01
  • because array is empty, so (Tile tile : tileArray) will not do anything... It will see empty array and execution will just move on... – Adnan Isajbegovic Apr 30 '16 at 15:40