java.lang.ArrayIndexOutOfBoundsException:-1我的java程序中出现错误

java.lang.ArrayIndexOutOfBoundsException:-1我的java程序中出现错误,java,Java,当我测试运行我的程序时,我似乎遇到了一个错误,上面写着java.lang.ArrayIndexOutOfBoundsException:-1 有谁能给我一些关于如何解决这个问题的建议吗 class MineFinderModel { public static int MINE_SQUARE = 10; public static int EMPTY_SQUARE = 0; int num_of_cols; int num_of_rows; int[][] the_minefield; pu

当我测试运行我的程序时,我似乎遇到了一个错误,上面写着java.lang.ArrayIndexOutOfBoundsException:-1

有谁能给我一些关于如何解决这个问题的建议吗

class MineFinderModel {
public static int MINE_SQUARE = 10;
public static int EMPTY_SQUARE = 0;

int num_of_cols;
int num_of_rows;
int[][] the_minefield;

public MineFinderModel(int n_cols, int n_rows) {
    num_of_rows = n_rows;
    num_of_cols = n_cols;
    the_minefield = new int[num_of_cols][num_of_rows];
}

public boolean addMine(int thisCol, int thisRow) {
    if (thisCol >= num_of_cols || thisRow >= num_of_rows)
        return false;
    if (the_minefield[thisCol][thisRow] == MINE_SQUARE)
        return false;
    the_minefield[thisCol][thisRow] = MINE_SQUARE;
    return true;
}

public int getValue(int thisCol, int thisRow) {
    if (thisCol >= num_of_cols || thisRow >= num_of_rows)
        return 0;
    return the_minefield[thisCol][thisRow];
}

public void addMinesToCorners() {
    the_minefield[0][0] = MINE_SQUARE;
    the_minefield[0][num_of_rows -1] = MINE_SQUARE;
    the_minefield[num_of_cols - 1][0] = MINE_SQUARE;
    the_minefield[num_of_cols - 1][num_of_rows - 1] = MINE_SQUARE;
}

}

我想它应该在“addMinesToCorners()”函数中,因为您没有测试边界。 试着在你周围放些if怎么样

if(num_of_cols == 0)
if(num_of_rows == 0)
在初始化时,这等于“0”,然后“0-1”给出“-1”。因此出现了错误


希望这有帮助

数组的索引为零,因此您的检查不正确,例如,如果num_of_cols为10,则最后一个位置将为9,但如果您将10作为thisCol传入,则您的检查将通过,因为它是根据初始化器值而不是数组的长度进行检查。 尝试将测试更改为

if (thisCol < 0  thisCol >= (num_of_cols - 1) || thisRow < 0 || thisRow >= num_of_rows - 1))
if(thisCol<0 thisCol>=(列数-1)| |列数<0 | |列数>=列数-1))

所有方法都有最大值检查,但没有一个方法检查thisRow和thisCol中的负值,因此如果这两个方法的任何参数为负值,addMine()和getValue()将抛出java.lang.ArrayIndexOutOfBoundsException。 您可以添加如下条件 `

if(thisCol>=num_cols | | thisCol<0

||thisRow>=num_of_rows | | thisRow在哪一行出现异常?显然是执行数组操作的函数之一(仅此而已)有一个算术错误。堆栈跟踪将有助于缩小它的范围。哪一行,如果它在
addMine
getValue
方法中,我们需要查看调用这些方法的代码。您没有发布足够的程序来让我们知道它试图做什么。当我在字段内外测试地雷时,它提供了是错误。同样,当条件计算为true时,他返回。不,Sam,如果无法添加地雷,他将返回false。如果满足其中任何一个条件,则返回false是正确的。也许你应该在向下投票之前正确阅读代码。尽管他应该像Amit所说的那样检查负值。我确实阅读了代码,我可以告诉你您现在知道,您的情况将以OP不会的方式导致超出范围的异常。
if (thisCol >= num_of_cols || thisCol < 0
            || thisRow >= num_of_rows || thisRow <0)

 return false