简体   繁体   English

无法在Java 2D数组中分配值-ArrayIndexOutOfBoundsException

[英]Can't assign value in Java 2D Array - ArrayIndexOutOfBoundsException

I'm having trouble assigning a value to my 2D array in Java. 我在用Java向2D数组分配值时遇到麻烦。 The last line of the code, theGrid[rowLoop][colLoop] = 'x'; 代码的最后一行, theGrid[rowLoop][colLoop] = 'x'; , is throwing an ArrayIndexOutOfBoundsException error. ,引发ArrayIndexOutOfBoundsException错误。 Could someone please explain why this is happening? 有人可以解释为什么会这样吗?

This is my code... 这是我的代码...

public class Main {
    public static char[][] theGrid;

    public static void main(String[] args) {
        createAndFillGrid(10,10);
    }

    public static void createAndFillGrid(int rows, int cols) {
        theGrid = new char[rows][cols];
        int rowLoop = 0;

        for (rowLoop = 0; rowLoop <= theGrid.length; rowLoop++) {
            int colLoop = 0;

            for (colLoop = 0; colLoop <= theGrid[0].length; colLoop++) {
                theGrid[rowLoop][colLoop] = 'x';
            }
        }
    }
}

Here is the problem rowLoop <= theGrid.length and colLoop <= theGrid[0].length . 这是问题rowLoop <= theGrid.lengthcolLoop <= theGrid[0].length It should be: 它应该是:

rowLoop < theGrid.length

and

colLoop < theGrid[0].length

The reason for the error is because your index is going up to the length of the array. 发生此错误的原因是因为您的索引将达到数组的长度。 So, if the length were 10, you go up to index 10. This is not a valid index into the array. 因此,如果长度为10,则升至索引10。这不是数组的有效索引。 Arrays have valid indices from 0 to length - 1 . 数组具有从0length - 1有效索引。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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