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.