I am making a Battleship game. So far, I have a implemented a Location class and a Grid class (the Locations constructor has no parameters, but will have default values for all of it's instance variables). The Grid class has an instance variable that is a 2D Array of Locations like:
private Location[][] grid;
What I want to do is make a constructor for the grid class that will make a grid (a 2D array of Location objects) and initialize each Location.
This is what I have made so far:
public Grid()
{
Location[][] grid = new Location[10][10];
for(int i = 0; i < 10; i++)
{
for(int j = 0; j < 10; j++)
{
grid[i][j] = new Location();
}
}
}
But when I use a method to get a location within the grid and try to print it out.
public Location getLocation(int row, int col)
{
return grid[row][col];
}
And attempt to use it in a the course's "tester" (and I have implemented a toString() method for Location objects)
Grid board = new Grid();
System.out.println(board.getLocation(0,0));
I get the error:
Exception in thread "main" java.lang.NullPointerException
at Grid.getLocation(Grid.java:24)
at GridTester.run(GridTester.java:9)
at ConsoleProgram.main(ConsoleProgram.java:21)
Is there a way that I can properly initialize every object within the 2D Array in a constructor?