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

时间:2013-03-13 15:42:14

标签: 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;

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

}

3 个答案:

答案 0 :(得分:1)

我猜它应该在“addMinesToCorners()”函数中,因为你没有测试边界。 如果试图在你周围放置一些变量呢?

if(num_of_cols == 0)
if(num_of_rows == 0)

初始化时,它等于“0”,然后“0 - 1”给出“-1”。因此错误。

希望这有帮助!

答案 1 :(得分:0)

数组是零索引的,所以你的检查是不正确的,例如,如果num_of_cols是10,那么最后一个位置将是9,但如果你传入10作为thisCol你的检查将通过,因为它检查初始值而不是长度数组。 尝试将测试更改为

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

答案 2 :(得分:0)

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

if (thisCol >= num_of_cols || thisCol < 0
            || thisRow >= num_of_rows || thisRow <0)

 return false