0

これは私のGridGeneratorクラスにあるコードです。目的は、最終的にマップに結合できる複数の長方形の部屋を作成することです。

int xRange, yRange;

//constructor
public GridGenerator(int xInput, int yInput) {
    xRange = xInput;
    yRange = yInput;
}

int[][] grid = new int[yRange][xRange];
//the first number indicates the number of rows, the second number indicates the number of columns
//positions dictated with the origin at the upper-left corner and positive axes to bottom and left

void getPosition(int x, int y) {
    int position = grid[y][x]; //ArrayIndexOutOfBoundsException here
    System.out.println(position);
}

これは私のMapperMainクラスにあるコードです。目的は、GridGeneratorインスタンスをマルチルーム マップに結合することです。今のところ、デバッグと足場の目的にも使用しています。

public static void main(String[] args) {

    GridGenerator physicalLayer1 = new GridGenerator(10,15);

    physicalLayer1.getPosition(0, 0); //ArrayIndexOutOfBoundsException here

}

ArrayIndexOutOfBoundsException エラーが発生しています。ある時点で、 にxRangeは 10 の値が割り当てられ、yRange15 の値が割り当てられます。クラスに値を割り当てても、問題はないようです。クラスでコンストラクターを使用すると、このエラーが発生します。xRangeyRangegridxRangeyRangeGridGeneratorMapperMain

4

3 に答える 3

4

問題は次の行です。

int[][] grid = new int[yRange][xRange];

コンストラクターの後にコーディングされているにもかかわらず、コンストラクターが実行されるに実行され、行が実行されると、サイズ変数のデフォルトの初期化値は0.

コンストラクターの前に実行される理由は、初期化順序によるものです。(とりわけ) すべてのインスタンス変数は、コンストラクターの実行前にコード化された順序で初期化されます。

この問題を解決するには、コードを次のように変更します。

// remove variables yRange and xRange, unless you need them for some other reason
int[][] grid;

public GridGenerator(int yRange, int xRange) {
    grid = new int[xRange][yRange];
}
于 2013-10-14T13:04:46.983 に答える
0
int[][] grid = new int[yRange][xRange]; 

配列の範囲に固定値を指定する必要があります。動的配列を探す場合は、配列リストを使用します

于 2013-10-14T13:13:47.373 に答える