[递增数组列表时的IndexOutOfBoundsException

问题描述 投票:0回答:1

我在我的编码分配中遇到了一个问题。我们的任务是根据交通数据读取两个txt文件,然后在美国为每个州创建对象,其中包含州ID代码,州名称和每个州的交通事故数量。

我相信我的代码几乎是完全正确的,但是在尝试打印最终产品(即我的arraylist中的每个对象)时,我一直收到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/LCRLystKStateaccidents.txt:https://pastebin.com/bDGDu4UQ

如果我可以提供其他任何信息来帮助您,请告诉我!这是我的第一篇文章,因此对于我的问题中有任何错误,我深表歉意,如果有需要,我将确保予以纠正。谢谢!

java arraylist indexoutofboundsexception
1个回答
0
投票

您遇到的麻烦是ArrayList.get方法是基于索引的,并且您正在使用状态ID中的值[[calculated,但不能保证它实际上是索引。

实际上,如果您查看Statecode.txt,它缺少状态ID3。因此,状态ID 1位于索引0,它可以正常工作。状态ID 4虽然在索引2处,但这会引起混乱。在列表中,缺少的项更多,因此State ID 56位于索引53(在此处有点猜测)。因此,当您对状态#56执行get(stateId -1)时,它也会执行get(55),这实际上超出了ArrayList的长度。

因此,您需要找到其他方式来获取该州的事故计数。我可以想到的一些选择:

    对于每个事故行,您可以遍历所有状态记录以找到具有匹配状态ID的记录。我不太喜欢这个主意。
  • 为您的statecode.txt数据添加文件,以便您的引用起作用(因此添加状态3,名称为“ unkown”)。篡改您的输入数据是一个坏主意,而期望获得完整的数据集也是一个坏主意。
  • 使用其他类型的集合。这就是我要做的,可能是java.util.Dictionary
© www.soinside.com 2019 - 2024. All rights reserved.