0
我正在为Common Meeting Times问题编写一个Java程序。我从文本文件中读取整数并将它们存储在主ArrayList中。文本文件看起来像这样,每一行的第一个数字表示在该行(不包括自身)的元素数:Java:ArrayOutOfBounds副作用?
6 6 7 2 4 5 9
5 1 3 4 8 7
9 10 12 11 9 8 4 3 2 6
然后我需要创建的文本文件的每一行的ArrayList,所以我有三个ArrayLists,我最终将用于CMT问题。看来,我的代码写的作品,并得到各行成自己的数组,但我有一些奇怪的东西要在第二while循环中......
package brt2356.CMT;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Scanner;
public class TestCMT {
public static void main(String[] args) throws FileNotFoundException {
ArrayList<Integer> array1 = new ArrayList<Integer>();
ArrayList<Integer> array2 = new ArrayList<Integer>();
ArrayList<Integer> array3 = new ArrayList<Integer>();
int value = 0; // first item in each line of text file
int items = 0; // counter for while loop
Scanner inFile = new Scanner(new File("C:/Users/me/workspace/cmt.txt"));
ArrayList<Integer> temp = new ArrayList<Integer>(); // master array
/* Read in values from file to master array */
while(inFile.hasNextInt()) {
temp.add(inFile.nextInt());
}
inFile.close();
value = temp.get(0); // first element of the first line in text file
while(temp != null) {
for(int i = 0; i < value; i++) {
array1.add(temp.get(i + 1));
items++;
}
System.out.println(array1 + " " + items + " " + value);
value = temp.get(items + 1); // first element of second line
for(int i = 0; i < value; i++) {
array2.add(temp.get(items + 2));
items++;
}
System.out.println(array2 + " " + items + " " + value);
value = temp.get(items + 2); // first element of third line
for(int i = 0; i < value; i++) {
array3.add(temp.get(items + 3));
items++;
}
System.out.println(array3);
}
}
}
我加了一些打印语句在while循环以确保我得到每个数组中的正确值。
我运行到IndexOutOfBoundsException和一些额外的打印问题。该程序的行为就像它有一个额外的打印语句......这很奇怪。我想如果我修复IndexOutOfBoundsException,那么另一个问题就会消失。
输出示例:
Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 30, Size: 23
at java.util.ArrayList.rangeCheck(Unknown Source)
at java.util.ArrayList.get(Unknown Source)
at brt2356.CMT.TestCMT.main(TestCMT.java:34)
[6, 7, 2, 4, 5, 9] 6 6
[1, 3, 4, 8, 7] 11 5
[10, 12, 11, 9, 8, 4, 3, 2, 6]
[6, 7, 2, 4, 5, 9, 6, 7, 2, 4, 5, 9, 5, 1, 3] 29 9
请问您可以发布输出吗? – Fildor 2014-11-23 21:16:26
你在哪里设置temp为空?你在第二时间使用它......而你根本不需要。 – Fildor 2014-11-23 21:18:36
我从不将temp设置为null。我想我应该在循环结束时做到这一点? – BrianRT 2014-11-23 21:23:35