处理一项任务,我应该将文件中的数据读入数组,以进行一些搜索/排序演示。
public class A5 {
public static void main(String[] args) throws FileNotFoundException, IOException {
fileToArray();
}
/**
* populates array from file
* @throws IOException
* @throws FileNotFoundException
*/
public static <T extends Comparable<T>> void fileToArray() throws IOException, FileNotFoundException {
int FileIndex = 0;
A5GItem[] gItems = new A5GItem[5150];
File file = new File("GroceryData.txt");
Scanner inputFile = new Scanner(file);
while (inputFile.hasNext()) {
String line = inputFile.nextLine().replace(" oz", "").replace("«", "");
String[] tokens = line.split(";");
if (tokens.length == 5) {
System.out.println(tokens[0]);
System.out.println(tokens[1]);
System.out.println(tokens[2]);
System.out.println(tokens[3]);
System.out.println(tokens[4]);
System.out.println(FileIndex);
FileIndex++;
else {
System.out.println("Bad line: " + line);}
} }`
我试图通过循环一些println语句来测试我是否正确填充了数组。它正确地标记列表中的前400个(大致)元素,然后只打印最后一个标记的一半并抛出
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 2
at A5.fileToArray(A5.java:59)
at A5.main(A5.java:16)
在经历了多次迭代的索引之后。不知道从哪里开始排除故障。
显然文件“GroceryData.txt”中的一行不包含5个令牌。请注意,方法split()
返回一个大小不是5的数组。因此不需要初始化变量tokens
。似乎变量FileIndex
计算读取的行数,所以我建议打印它以及在tokens
之后打印数组split()
的大小,例如
while (inputFile.hasNext()) {
String line = inputFile.nextLine().replace(" oz", "").replace("«", "");
String[] tokens = line.split(";");
FileIndex++;
System.out.println("Line: " + FileIndex + " has " + tokens.length + " tokens.");
}
然后你会发现文件的哪一行不是你想象的那样。
顺便说一句,关于评论者提到的命名惯例,它只是 - 一个约定。这不是导致你的ArrayIndexOutOfBoundsException
的原因
您发布的堆栈跟踪也表示代码的第59行包含问题。我相信这就是这条线......
System.out.println(tokens[2]);
打印数组的元素假设它包含5个元素,但正如我和其他人所提到的,方法split()
可能不会返回5元素数组。