This question already has answers here:
What causes a java.lang.ArrayIndexOutOfBoundsException and how do I prevent it?

(25个答案)


在10个月前关闭。





因此,我正在尝试创建一个单元格网格,每个单元格都可以作为自己的onTouch对象。我遇到了很多问题,但主要的问题是在尝试填充单元格的列和行时发生的此异常。现在,我正在尝试实现一个Try / Catch方法来解决它,但是还没有运气。我想如果我从(j)中减去列数,可能会阻止最后两列的填充(实际上,我知道那是行不通的)。

无论如何,这是代码:

// creates cells
NavCell[][] mCells = new NavCell[mCellCols][mCellRows];
//System.out.println( "Rows " + mCellRows + " and Cols: " + mCellCols);
for (int j = 0; j < 18; j++)
{
    System.out.println("inside rows       " + j);
    if (mCells[j] != null)
    {
        for (int i = 0; i < mCellCols; i++)
        {
            System.out.println("inside columns      " + i);

            mCells[j][i] = new NavCell();
            mCells[j][i].setBounds(
                i * CELL_SIZE,
                j * CELL_SIZE,
                (i * CELL_SIZE) + CELL_SIZE,
                (i * CELL_SIZE) + CELL_SIZE);
            // drawCells(i, j);
            // System.out.println( "Lazer-3 " + CELL_SIZE);
            // System.out.println( "Lazer-4 " + i);

            System.out.println("Hello Dude" + j );
            Canvas canvas = new Canvas();
            drawCells(canvas, j, i);
        }
        try {
            int Z = j - 2;
            j = Z;
            System.out.println("Hello Matt" + j );
        } catch (ArrayIndexOutOfBoundsException e) {
            Log.e("MainActivity", "Reading list of NavCells failed!", e);
        }
    }

    System.out.println("Lazer-2 " + mCells);
}

最佳答案

有问题,您声明了NavCell[][] mCells = new NavCell[mCellCols][mCellRows];,但不是那样。

您需要声明NavCell[][] mCells = new NavCell[mCellRows][mCellCols];是第一个行,然后是列

因此,for将会像:

-- here you just go for all the rows --

for (int i = 0; i < mCellRows; i++){



     --here you go for all the columns in each row --

     for(int a = 0; a < mCelCols; a++){

     }
}

08-04 20:35