【问题标题】:Index out of bounds exception but the size and index are the same索引越界异常但大小和索引相同
【发布时间】:2017-08-04 10:37:46
【问题描述】:

这段代码是关于一个水罐车在一个环境中徘徊寻找有任务的水站。

尝试通过访问点的 ArrayList 递增,但每次运行代码时,我都会得到一个“IndexOutOfBoundsException”,但在不同的索引处,并且大小始终与索引相同,所以我很困惑。破坏程序的索引/大小似乎是随机变化的。

示例错误: 线程“主”java.lang.IndexOutOfBoundsException 中的异常:索引:5,大小:5

相关代码(假设无限运行):

int stationIncrementer = 0;
ArrayList<Point> stationList = new ArrayList<Point>();
ArrayList<Point> wellList = new ArrayList<Point>();
Iterator it = stationList.iterator();

public Action senseAndAct(Cell[][] view, long timestep) {

    // Loop to scan every cell in view for stations
    int i = 0, j = 0;
    for (i = 0; i < 25; i++) {
        for (j = 0; j < 25; j++) {
            Cell c = view[i][j];
            if (view[i][j] instanceof Station) {
                Task t = ((Station) c).getTask();
                Point p = view[i][j].getPoint();
                if (stationList.contains(p)) {
                    break;
                } else if (t != null) {
                    stationList.add(p);
                }
            }
            if (j == 25) {
                j = 0;
            }
    }
}

if (it.hasNext() && stationList.get(stationIncrementer) != null && getWaterLevel() > 0
            && !(getCurrentCell(view) instanceof Station)) {
        Point p = stationList.get(stationIncrementer);
        stationIncrementer++;
        return new MoveTowardsAction(p);

    }

【问题讨论】:

  • 索引是从 0 开始的,例如大小 5 只有有效索引 0..4
  • 你能看出索引随机超出范围的任何原因吗?正如我所说,错误发生在几个不同的值上
  • 不,因为你没有显示view[][]的初始化代码
  • view 只是 Cell 的实例化,它只是一个 2D 数组
  • 这段代码也不应该捕获 OutOfBoundsException 吗?: if (it.hasNext() && stationList.get(stationIncrementer) != null

标签: java arraylist indexoutofboundsexception


【解决方案1】:

您的条件 if(j==25) 永远不会执行,因为定义的 for 循环条件是 j

【讨论】:

  • 谢谢忘了把它拿出来,虽然并没有真正解决我的问题
  • 虽然您认为代码无法访问是正确的,但它与问题和问题无关。您应该将此类信息作为评论发布,而不是作为答案发布,这意味着对问题的实际回答。
  • 知道了。谢谢你
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-11-19
  • 2013-03-30
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多