java如何读取文件,然后将每个文件整数分配给数组列表?
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个数组列表,并将数据放入其中。但我似乎不明白。它总是给我一个例外。此外,我需要能够将数据放入另一种方法中。例如“Quad(ax,ay,bx,by,cx,cy,dx,dy)”,每个文件都有我需要的坐标。数组列表是实现它的最佳方式吗
# 1 楼答案
在使用ArrayList之前,需要将内存分配给它们
这就是它将NullPointerException作为文本文件[0]抛出的原因,。。。都是空的,而您正试图对空值执行操作