Trey Trey - 1 year ago 58
Java Question

How to read files and then assign each file integer to an array list?

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 ++;
}
}
}


I need to open files (.txt and .in) that are given as an array. I use a for loop to loop through them and then open them, but as I read through them I want to use the data from them. So my idea was to create 5 array list and put the data in those. But I can't seem to figure it out. It keeps giving me NullPointer Exception. Also, I need to be able to put the data into another method. An example would be "Quad(ax, ay, bx, by, cx, cy, dx, dy)" and each file has the coordinates I need. Is the array list the best way to accomplish it?

Answer Source

You need to allocate memory to arraylists before using them.

This is the reason why it threw NullPointerException as textFiles[0],... are null, and you're trying to perform operation on a 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());       
        }