簡體   English   中英

遞增 ArrayList 時出現 IndexOutOfBoundsException

[英]IndexOutOfBoundsException When Incrementing ArrayList

我遇到了編碼作業中出現的問題。 我們的任務是根據交通數據讀取兩個 txt 文件,然后為美國的每個州創建對象,其中包含州 ID 代碼、州名和每個州的交通事故數量。

我相信我的代碼幾乎完全正確,但是在嘗試打印我的最終產品時,我不斷收到 IndexOutOfBoundsException,這是我的數組列表中的每個對象。

這是我的代碼:

    import java.util.*;
    import java.io.*;
    public class OuterMain {

    public static void main(String[] args) throws  IOException{

        String line;

        ArrayList<StateAccident> stateData = new ArrayList <StateAccident>();


        File file = new File("StateCode.txt");
        FileReader fileReader = new FileReader(file);
        BufferedReader br = new BufferedReader(fileReader);


        br.readLine();
        while((line = br.readLine())!=null){

            String arr[] = line.split(" ");
            int stateCode = Integer.parseInt(arr[0]);   
            String stateName = arr[1];
            StateAccident accidents = new StateAccident(stateCode,stateName);
            stateData.add(accidents);


        }

        File stateAccidentsFile = new File("StateAccidents.txt");
        fileReader = new FileReader(stateAccidentsFile);
        br = new BufferedReader(fileReader);
        line = null;

        br.readLine();  
        while((line=br.readLine())!=null){ 

            String arr[] = line.split(" ");

            int stateID = Integer.parseInt(arr[0]);

            stateData.get(stateID-1).incrementAccidentCount();

        }   


        for(StateAccident accidents : stateData){
            System.out.println(accidents.toString());
        }



    }

}

給我錯誤的那一行是:

stateData.get(stateID-1).incrementAccidentCount();

我真的很感激這方面的一些幫助,因為我覺得這是一個簡單的修復,但我已經被它難住了幾個小時,真的不知道還能嘗試什么。

這是我正在閱讀的兩個文本文件:

Statecode.txt: https: //pastebin.com/LCRLystK Stateaccidents.txt: https ://pastebin.com/bDGDu4UQ

如果我可以提供任何其他信息來幫助您,請告訴我! 這是我的第一篇文章,所以如果我的問題中有任何錯誤,我深表歉意,如果需要,我一定會糾正它們。 謝謝!

您遇到的問題是ArrayList.get方法是基於索引的,並且您使用的是根據狀態 id計算的值,這不能保證實際上是索引。

事實上,如果你查看 Statecode.txt,它缺少狀態 id 3。所以狀態 id 1 位於索引 0 處,它恰好可以工作。 狀態 id 4 雖然在索引 2 處,這會引起混淆。 當您在列表中找到時,缺少更多,因此狀態 id 56 位於索引 53(在那里猜測)。 因此,當您對狀態 #56 執行get(stateId -1) ,它執行get(55) ,實際上超出了 ArrayList 的長度。

因此,您需要找到一種不同的方法來獲取該州的事故計數。 我能想到的幾個選項:

  • 對於每個事故行,您可以遍歷所有狀態記錄以找到具有匹配狀態 ID 的記錄。 我不太喜歡這個主意。
  • 修改您的 statecode.txt 數據,以便您的參考工作(因此添加狀態 3,名稱為“unkown”)。 篡改您的輸入數據是一個壞主意,期望一組完整的數據也是一個壞主意。
  • 使用不同類型的集合。 這就是我要做的,可能是 java.util.Dictionary

暫無
暫無

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

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