Проверка на null в массиве 2D-объектов

Я работаю над классным проектом, в котором мне нужно создать игру. У меня есть два класса, BoardButton и TreasureButton, которые создают кнопки; Класс TreasureButton расширяет класс BoardButton.

В классе, над которым я работаю, я пытаюсь создать панель, содержащую 2D-массив (10x10) с 20 случайно выбранными экземплярами класса TreasureButton, а оставшиеся 80 экземпляров класса BoardButton. Когда я запускаю программу, я получаю сообщение об ошибке выполнения:

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

Код в строке, где возникает ошибка:

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

Поскольку я не инициализировал массив, я считаю, что значение в выбранных индексах массива должно быть установлено равным нулю. Любая помощь будет принята с благодарностью.

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
Пользовательский скаляр GraphQL
Пользовательский скаляр GraphQL
Листовые узлы системы типов GraphQL называются скалярами. Достигнув скалярного типа, невозможно спуститься дальше по иерархии типов. Скалярный тип...
Как вычислять биты и понимать побитовые операторы в Java - объяснение с примерами
Как вычислять биты и понимать побитовые операторы в Java - объяснение с примерами
В компьютерном программировании биты играют важнейшую роль в представлении и манипулировании данными на двоичном уровне. Побитовые операции...
Поднятие тревоги для долго выполняющихся методов в Spring Boot
Поднятие тревоги для долго выполняющихся методов в Spring Boot
Приходилось ли вам сталкиваться с требованиями, в которых вас могли попросить поднять тревогу или выдать ошибку, когда метод Java занимает больше...
Полный курс Java для разработчиков веб-сайтов и приложений
Полный курс Java для разработчиков веб-сайтов и приложений
Получите сертификат Java Web и Application Developer, используя наш курс.
1
0
50
2
Перейти к ответу Данный вопрос помечен как решенный

Ответы 2

Ответ принят как подходящий

Вы не указываете верхнюю границу с new Random(10).

От 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).

И от Javadoc из nextInt() (акцент мой)

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.

Это причина вашего ArrayIndexOutOfBoundsException.

Вам нужно использовать перегруженный метод nextInt, который принимает верхнюю границу.

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

Другая проблема (как указано в другой ответ) - Вы неправильно указали имена переменных счетчика цикла за.

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

должно быть

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

Вот что это было. Раньше я использовал класс Random только один раз и напортачил, думая, что объявил верхнюю границу при создании нового случайного объекта. Спасибо вам за помощь

Jon 02.12.2018 06:09

Строка и столбец должны быть от 0 до 9 и никогда не должны достигать 10. Вы уверены, что заменили row++ на col++ во вложенном цикле?

user7 02.12.2018 06:15

Параметр в конструкторе Random - это seed, что предотвращает генерацию одной и той же последовательности каждый раз, но не имеет ничего общего с диапазоном случайного целого числа.

В большинстве случаев вам не нужно устанавливать семя, просто используйте new Random(), и java обработает семя сама.

Чтобы ограничить сгенерированный номер от 0 до 9, вы должны вызвать randomNumber.nextInt(10) вместо randomNumber.nextInt().

Другие вопросы по теме