处理数组中的对象时出现OutOfBounds [英] OutOfBounds when working with objects in an array

查看:94
本文介绍了处理数组中的对象时出现OutOfBounds的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我创建一个 Example 对象的数组时,我调用类似 initializeArray(); 的东西,我使用一个简单的嵌套for循环遍历该数组,然后分配使用 exampleArr [i] [j] = new Example(false,false,false,0); 创建具有数组每个索引值的新对象.上面一行中的lang.ArrayIndexOutofBoundsException:0 .

When I am creating an array of Example objects, I call something like initializeArray(); I use a simple nested for loop to traverse through the array and then assign new objects with values to each index of the array using exampleArr[i][j] = new Example(false, false, false, 0); however, calling this gives me an java.lang.ArrayIndexOutofBoundsException:0 at the line above.

我假设我错误地实例化了新对象,因为这在另一种方法中也会发生,该方法应该显示数组中的所有 Example 对象.但是,我将发布我正在使用的嵌套循环,以防万一我做错了一些我看不到的东西.

I am assuming that I am instantiating the new object incorrectly, as this also happens in another method which is supposed to display all of the Example objects in the array. However, I will post the nested loop I am using in case there is something that i've done wrong that I can't see.

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

感谢大家的帮助!问题已经解决.

Thanks everyone for your help! The problem has been solved.

推荐答案

在顶部声明您的 tileArr ,但不要初始化.

Declare your tileArr at the top but do not initialize.

Tile[][] tileArr; 

然后在 initializeArray()中的 for 循环之前初始化数组(这是假设您的已设置.您也可以添加逻辑进行检查).

Then initialize your array before your for loop in the initializeArray() (This is assuming your rows and columns is set. You can add logic to check this as well).

tileArr = new Tile[getRows()][getColumns()];
tileArr = new Tile[rows][columns]; //Do this instead if you don't want the print statements to be called

这篇关于处理数组中的对象时出现OutOfBounds的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆