当我创建 Example
数组时对象,我称之为 initializeArray();
我使用一个简单的嵌套 for 循环来遍历数组,然后使用 exampleArr[i][j] = new Example(false, false, false, 0);
将带有值的新对象分配给数组的每个索引。然而,调用它给了我一个 java.lang.ArrayIndexOutofBoundsException:0
在上面的行。
我假设我错误地实例化了新对象,因为这也发生在另一种应该显示所有 Example
的方法中。数组中的对象。但是,我将发布我正在使用的嵌套循环,以防万一我做错了一些我看不到的事情。
public void initializeArray(){
for(int i = 0; i < getRows(); i++){
for(int j = 0; j < getColumns(); j++){
tileArr[i][j] = new Tile(false, false, false, 0);
}
}
}
//行和列的声明
private int rows;
private int columns;
Tile[][] tileArr = new Tile[rows][columns];
public void setRows(int r)
{
rows = r;
}
public void setColumns(int c)
{
//various setters and getters for the array
columns = c;
}
public int getRows()
{
System.out.print(rows);
return rows;
}
public int getColumns()
{
System.out.print(columns);
return columns;
}
感谢大家的帮助!问题已解决。
最佳答案
在顶部声明您的tileArr
,但不初始化。
Tile[][] tileArr;
然后在 initializeArray()
中的 for
循环之前初始化数组(假设您的行
和列
code> 已设置。您也可以添加逻辑来检查这一点)。
tileArr = new Tile[getRows()][getColumns()];
tileArr = new Tile[rows][columns]; //Do this instead if you don't want the print statements to be called
关于java - 处理数组中的对象时出现越界,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33173400/