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