我在我的编码分配中遇到了一个问题。我们的任务是根据交通数据读取两个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
如果我可以提供其他任何信息来帮助您,请告诉我!这是我的第一篇文章,因此对于我的问题中有任何错误,我深表歉意,如果有需要,我将确保予以纠正。谢谢!
您遇到的麻烦是ArrayList.get
方法是基于索引的,并且您正在使用状态ID中的值[[calculated,但不能保证它实际上是索引。
get(stateId -1)
时,它也会执行get(55)
,这实际上超出了ArrayList的长度。因此,您需要找到其他方式来获取该州的事故计数。我可以想到的一些选择: