简体   繁体   中英

How to initialize an array of objects within a constructor?

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?

Your instance variable and local variable (in constructor) have the same name. Whenever you call the constructor the grid variable in the constructor is shadowing the instance variable. Remove the type declaration in your constructor, ie Location[][]

private Location[][] grid;

    
public Grid()
{
    grid = new Location[10][10];
    for(int i = 0; i < 10; i++)
    {  .....

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM