I'm wondering how to add items (from a Scanner that reads file input item by item) to an array list of arrays. Right now Eclipse is telling me that my .add does not work and I'm assuming it's because of the array list of arrays. Please help!
public static void readInputFile(String fileName,
ArrayList<ArrayList<String> > fileByLine) throws IOException {
try {
FileInputStream fileInput = new FileInputStream(fileName);
Scanner fileIn = new Scanner(new FileReader(fileName));
String fileWord = fileIn.next();
while (fileIn.hasNext()) {
fileByLine.add(fileWord);
fileWord = fileIn.next();
}
}
catch (IOException ex) {
System.out.println("Error reading file.");
}
}
This obviously won't work.. You're adding a String to an ArrayList that's expecting an ArrayList element (not a string element). Best you do something like this:
try {
FileInputStream fileInput = new FileInputStream(fileName);
Scanner fileIn = new Scanner(new FileReader(fileName));
String fileWord = fileIn.next();
ArrayList<String> newSubList = new ArrayList<>();
while (fileIn.hasNext()){
fileWord = fileIn.next();
//Adds to this specific Arraylist:
newSubList.add(fileWord);
}
//Adds to the outermost ArrayList after loop
fileByLine.add(newSubList);
}
catch (IOException ex) {
System.out.println("Error reading file.");
}
I hope this helps... Merry coding!