这是我的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,而yRange被赋值为15。但是,当我尝试使用xRangeyRange作为grid的参数时,Java出现了一些问题这样,我不确定为什么。如果在xRange类中为yRangeGridGenerator分配值,似乎没有问题。当我在MapperMain类中使用构造函数时,出现此错误。

最佳答案

问题是这一行:

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


尽管在构造函数之后编码,但在构造函数执行之前执行,并且在执行该行时,size变量的默认初始化值为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];
}

关于java - 二维整数数组不接受我提供的尺寸,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/19360830/

10-09 20:33