【发布时间】:2013-09-30 10:12:50
【问题描述】:
我不是 Java 的初学者,但我也不是专家,这就是我发布此内容以寻求帮助/解释的原因。我在互联网上找了很多地方,都没有我想要的答案。
public class Driver {
public static ArrayList<ArrayList<Integer>> theData; // ArrayList to store the ArrayList of values
final static int dataSize = 20; // length of the line of data in the inFile
/***
* Read in the data from the inFile. Store the current line of values
* in a temporary arraylist, then add that arraylist to theData, then
* finally clear the temporary arraylist, and go to the next line of
* data.
*
* @param inFile
*/
public static void getData(Scanner inFile) {
ArrayList<Integer> tempArray = new ArrayList<Integer>();
int tempInt = 0;
while (inFile.hasNext()) {
for (int i = 0; i < dataSize; i++) {
tempInt = inFile.nextInt();
tempArray.add(tempInt);
}
theData.add(tempArray);
tempArray.clear();
}
}
/**
* @param args
*/
public static void main(String[] args) {
Scanner inFile = null;
theData = new ArrayList<ArrayList<Integer>>();
System.out.println("BEGIN EXECUTION");
try {
inFile = new Scanner(new File("zin.txt"));
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
getData(inFile);
}
System.out.println(theData.get(5).get(5)); // IndexOutOfBoundsException here
System.out.println("END EXECUTION");
}
}
我得到一个 IndexOutOfBoundsException 我标记它的地方。有趣的是,当我试图弄清楚这一点时,我测试了 getData 方法是否正常工作,因此当该方法在 getData 的 while 循环中迭代时,我打印出了数组-theData,以及数组theData 中数组的大小,你知道吗,它返回了正确的大小和值。所以基本上当getData被调用时,它可以正常工作并存储值,但是当我尝试调用Main中的值时,ArrayList中没有值。
当我清除我曾经添加到theData 的tempArray 时,我感觉这与此有关。任何帮助都会很棒!
谢谢
【问题讨论】:
标签: java eclipse arraylist indexoutofboundsexception