繁体   English   中英

数组索引超出范围? 怎么样?

[英]Array index out of bounds? How?

您好stackoverflow的好人! 我有一个我无法理解的怪异问题。 我要发布两个有问题的方法:

private static void resi(int [][] matrica,int row, int col) {
    if (matrica[row][col] != 0) {
        next(matrica,row, col); // <--- this the line that first throws the exception
    } else {
        for (int num = 1; num < 10; num++) {
            if (checkRow(matrica,row, num) && checkColumn(matrica,col, num) && checkBox(matrica,row, col, num)) {
                matrica2[row][col] = num;
                matrica4[row][col] = num;
                next(matrica,row, col);
            }
        }
        matrica[row][col] = 0;

    }
}

而另一个:

 private static void next(int [][] matrica2,int row, int col) {
    if (col < 8) {
        resi(matrica2,row, col + 1);
    } else {
        resi(matrica2,row + 1, 0);
    }
}

因此,我正在根据我在网上找到的一些代码制作数独求解器。 现在,当我尝试调试程序时,我可以很好地遍历某些行(并且按预期运行),但是一旦程序首次到达“ resi”方法中对“ next”方法的调用,它将崩溃,并出现数组索引边界异常。 如果我只是尝试在不调试的情况下运行程序,则在NetBeans的输出选项卡中,同一方法一遍又一遍地调用时,会出现很多“数组索引超出范围”异常。

我不知道是什么导致了该错误。 据我所知,row和col不会超过0-8范围... 2D数组一定有问题吗? 感谢您的时间。

编辑1:

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 9 
at SudokuGame.Main.resi(Main.java:88)
    at SudokuGame.Main.next(Main.java:107)
    at SudokuGame.Main.resi(Main.java:89)
    at SudokuGame.Main.next(Main.java:105)
    at SudokuGame.Main.resi(Main.java:95)

...依此类推,它们在重复,因为似乎正在遍历代码并不断抛出异常?

执行程序将确切说出发生问题的那一行。 看代码,我猜想在next一些调用之后, resi方法的第三行( next(matrica,row, col); )将抛出执行,因为它错过了对该行的某些验证。 我们可以确定的是,将执行程序粘贴到如pastebin.com之类的网站上,并在此处通知我们看到它=)

next()您一直在递增row但是没有像col那样对row故障保护索引的边界检查,因此不能保证row值将大于8,即9。

因此,请确保在行resi(matrica2,row + 1, 0); )中增加( row+1 )之前检查row是否小于8 resi(matrica2,row + 1, 0);

private static void next(int [][] matrica2,int row, int col) {
if (col  8) {
    resi(matrica2,row, col + 1);
} else if(row < 8) { // Make sure to increment row only if less than 8
    resi(matrica2,row + 1, 0);
} else {
    // Stop the application (May Be)
 }

}

暂无
暂无

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

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