remindmyself
remindmyself

Reputation: 21

Testing for null in a 2D object array

I'm working on a class project where I have to create a game. I have two classes, BoardButton and TreasureButton, which create buttons; the TreasureButton class extends the BoardButton class.

In the class I'm working on, I'm trying to create a panel that contains a 2D array (10x10) with 20 randomly selected instances of the TreasureButton class, while the remaining 80 instances of the BoardButton class. When I run the program, I get a runtime error of:

java.lang.ArrayIndexOutOfBoundsException: -1157793070
    at GameBoardPanel.<init>(GameBoardPanel.java:46)
    at TreasureGame.<init>(TreasureGame.java:22)
    at TreasureGame.main(TreasureGame.java:33)

The code at the line where the error is thrown is:

if (gameBoardButtons[row][col] == null)

Since I haven't initialized the array, I believe the value at the chosen indices of the array should be set to null. Any help would be greatly appreciated.

public class GameBoardPanel extends JPanel
{
    private BoardButton[][] gameBoardButtons;       // BoardButton 2D array that will be used to populate the board
    private final int NUM_TREASURE_BUTTONS = 20;    // Number of treasure buttons that will be added to the array
    private final int NUM_ROWS = 10;                // Number of rows in the array
    private final int NUM_COLS = 10;                // Number of columns in the array

    public GameBoardPanel()
    {
        int treasureButtonInstances = 0;            // Used to count the number of TreasureButton instances

        // Create the 'gameBoardButtons' array and make it a 10x10 array
        gameBoardButtons = new BoardButton[NUM_ROWS][NUM_COLS];

        // Build an object from the Random class that chooses a number between 0-9
        Random randomNumber = new Random(10);

        // Build a while loop that randomly adds 20 different TreasureButton instances to the 'gameBoardButtons' BoardButton array
        while (treasureButtonInstances < NUM_TREASURE_BUTTONS)
        {
            // Obtain two random numbers that will be used to assign a TreasureButton instance to the 'gameBoardButtons' BoardButton array
            int row = randomNumber.nextInt();
            int col = randomNumber.nextInt();

            // If statement that adds an instance of the TreasureButton class if that particular row/column of the 'gameBoardButtons' BoardButton array is empty
            if (gameBoardButtons[row][col] == null)
            {
                // Create an instance of the TreasureButton class and assign it to the particular row/col of our 'gameBoardButtons' BoardButton array
                gameBoardButtons[row][col] = new TreasureButton();

                // Increment the 'treasureButtonInstances' variable, as an instance of the TreasureButton class has been created
                treasureButtonInstances++;
            }// End of the if statement
        }// End of the while loop

        // Build a nested for loop that will populate the rest of the 'gameBoardButtons' BoardButton array
        for (int row = 0; row < NUM_ROWS; row++)
        {
            for (int col = 0; row < NUM_COLS; row++)
            {
                // If statement that will assign an instance of the BoardButton class if that particular row/col of our 'gameBoardButtons" BoardButton array is empty
                if (gameBoardButtons[row][col] == null)
                {
                    // Create an instance of the BoardButton class and assign it to the particular row/col of our 'gameBoardButtons' BoardButton array
                    gameBoardButtons[row][col] = new BoardButton();
                }// End of the if statement
            }//End of the nested for loop
        }// End of the for loop
    }// End of the GameBoardPanel no-arg constructor

Upvotes: 1

Views: 76

Answers (2)

Jeffrey Chen
Jeffrey Chen

Reputation: 1967

The parameter in the constructor of Random is seed, which prevents generating same sequence every time, but has nothing to do with the range of the random integer.

In most of the cases, you don't have to set the seed, just use new Random() and java will handle the seed by itself.

To limit the generated number in 0 to 9, you should call randomNumber.nextInt(10) instead of randomNumber.nextInt().

Upvotes: 0

Thiyagu
Thiyagu

Reputation: 17890

You are not specifying an upper bound with new Random(10).

From javadoc

Creates a new random number generator using a single long seed. The seed is the initial value of the internal state of the pseudorandom number generator which is maintained by method next(int).

And from the Javadoc of nextInt() (emphasis mine)

Returns the next pseudorandom, uniformly distributed int value from this random number generator's sequence. The general contract of nextInt is that one int value is pseudorandomly generated and returned. All 232 possible int values are produced with (approximately) equal probability.

This is the reason for your ArrayIndexOutOfBoundsException.

You need to use the overloaded method of nextInt that takes an upper bound.

int row = randomNumber.nextInt(NUM_ROWS);
int col = randomNumber.nextInt(NUM_COLS);

Another issue (as pointed out in the other answer) - You got the for loop counter variable names wrong

for (int col = 0; row < NUM_COLS; row++)

must be

for (int col = 0; col < NUM_COLS; col++)

Upvotes: 1

Related Questions