-6

プログラムの実行をテストすると、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;
}

}

4

3 に答える 3

1

境界をテストしていないので、「addMinesToCorners()」関数にあるはずだと思います。あなたの周りに if 変数を入れてみるのはどうですか?

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

初期化時にはこれは「0」に等しく、「0 - 1」は「-1」になります。したがって、エラー。

お役に立てれば !

于 2013-03-13T15:45:32.407 に答える
0

配列はゼロ インデックスであるため、チェックは正しくありません。たとえば、num_of_cols が 10 の場合、最後の位置は 9 になりますが、配列の長さではなくイニシャライザ値に対してチェックしているため、thisCol として 10 を渡すとチェックに合格します。 . テストを次のように変更してみてください

if (thisCol < 0  thisCol >= (num_of_cols - 1) || thisRow < 0 || thisRow >= num_of_rows - 1))
于 2013-03-13T15:50:31.383 に答える
0

すべてのメソッドには最大値チェックがありますが、thisRow と thisCol の負の値をチェックするメソッドはありません。したがって、これら 2 つのメソッドの引数のいずれかが負の場合、addMine() と getValue() は java.lang.ArrayIndexOutOfBoundsException をスローします。 . `のような条件を追加できます

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

 return false
于 2013-03-13T16:07:09.520 に答える