java - 无法在 Java 二维数组中赋值 - ArrayIndexOutOfBoundsException

标签 java arrays indexoutofboundsexception

我在用 Java 为二维数组赋值时遇到问题。代码的最后一行 theGrid[rowLoop][colLoop] = 'x'; 引发了 ArrayIndexOutOfBoundsException 错误。有人可以解释为什么会这样吗?

这是我的代码...

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';
            }
        }
    }
}

最佳答案

这里是问题rowLoop <= theGrid.lengthcolLoop <= theGrid[0].length .应该是:

rowLoop < theGrid.length

colLoop < theGrid[0].length

错误的原因是因为你的索引上升到数组的长度。因此,如果长度为 10,则索引为 10。这不是数组的有效索引。数组具有来自 0 的有效索引至 length - 1 .

关于java - 无法在 Java 二维数组中赋值 - ArrayIndexOutOfBoundsException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5303530/

相关文章:

java - 如何将我的 Json 更改为 Html 输出

arrays - 初始化器避免将空数组作为参数

java - Android ListView 数组索引越界异常 - 没有线索?

java - Kotlin - 从 Java 转换时出现 IndexOutOfBoundsException

java - 仅当通过 JAX-RS 调用时才出现 Hibernate 错误

java - 无法在数组中找到五个最低值...最大值有效,而最小数组未分配值

c++ - 线程安全无锁数组

java - While 循环无法正常工作。 ArrayIndexOutOfBoundsException

java - 使用@Loggable jcabi 注释进行日志记录会修剪日志

php - RecursiveIteratorIterator - 格式化数组