import java.io.File;
import java.util.ArrayList;
import java.util.Scanner;
public class NotWorking {
public static void main(String[] args) throws Exception{
// The files that I need to open
// They contain integers (points on a graph)
// Ex: 74 0 80 100 150 60 150
String[] names = {"Test.txt", "Test2.in", "test3.in", "Test4.in", "Test5.in"};
// Create 5 list
ArrayList<Integer>[] textFiles = new ArrayList[5];
// for loop through each file
for (int i = 0; i < names.length; i++) {
Scanner scanner;
// open file
scanner = new Scanner(new File(names[i]));
// @fileNumber is one of 5 list
int fileNumber = 0;
// add each integer to the correct list
while (scanner.hasNextInt()){
// line below this is where it says NullPointer Exception
textFiles[fileNumber].add(scanner.nextInt());
}enter code here
// Trying to see if lists are made correctly and also increasing fileNumber after
// each file is processed
System.out.println(textFiles[fileNumber]);
fileNumber ++;
}
}
}
我需要打开以数组形式给出的文件(.txt和.in)。我使用for循环遍历它们,然后打开它们,但是当我阅读它们时,我想使用它们中的数据。所以我的想法是创建5个数组列表并将数据放入其中。但我似乎无法弄清楚。它一直给我NullPointer异常。另外,我需要能够将数据放入另一种方法中。一个例子是“ Quad(ax,ay,bx,by,cx,cy,dx,dy)”,每个文件都有我需要的坐标。数组列表是实现它的最佳方法吗?
您需要在使用数组列表之前为数组列表分配内存。
这就是为什么它将NullPointerException抛出为textFiles [0],...为null,并且您试图对null执行操作的原因!
textFiles[fileNumber] = new ArrayList<Integer>();
// call constructor as above to allocate memory to each individual arraylists.
while (scanner.hasNextInt()){
textFiles[fileNumber].add(scanner.nextInt());
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句