简体   繁体   English

索引超出范围异常,但大小和索引相同

[英]Index out of bounds exception but the size and index are the same

This code is about a water tanker wandering an environment looking for water stations that have tasks. 这段代码是关于一个水轮在一个环境中徘徊,寻找有任务的水站。

Trying to increment through an ArrayList of points to visit but every time I run the code I get an "IndexOutOfBoundsException" but at different indexes and the size is always the same as the index so I am very confused. 尝试增加要访问的点的ArrayList,但是每次运行代码时,都会得到“ IndexOutOfBoundsException”,但索引不同,并且大小始终与索引相同,所以我很困惑。 The index/size that break the program appear to change randomly. 破坏程序的索引/大小似乎是随机变化的。

Example error: Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 5, Size: 5 错误示例:线程“主”中的异常java.lang.IndexOutOfBoundsException:索引:5,大小:5

Relevant code(Assume it runs infinitely): 相关代码(假设它无限运行):

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

    }

您的条件if(j == 25)将永远不会执行,因为定义的循环条件是j <25,请更正它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM