简体   繁体   中英

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. The index/size that break the program appear to change randomly.

Example error: Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 5, Size: 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,请更正它。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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