簡體   English   中英

索引超出范圍異常,但大小和索引相同

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

這段代碼是關於一個水輪在一個環境中徘徊,尋找有任務的水站。

嘗試增加要訪問的點的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);

    }

您的條件if(j == 25)將永遠不會執行,因為定義的循環條件是j <25,請更正它。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM