3

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.");
    }

}
punchkey
  • 81
  • 1
  • 11

2 Answers2

1

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!

Taslim Oseni
  • 6,086
  • 10
  • 44
  • 69
0

you can do it.

add first a new List to the father List then add items

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();

            ArrayList<String> list = new ArrayList<>(); //list of items
            while (fileIn.hasNext()) {
                fileWord = fileIn.next();
                list.add(fileWord); //adding item to list

            }
            fileByLine.add(list); //add list with list to father list
        } catch (IOException ex) {
            System.out.println("Error reading file.");
        }

    }
Taslim Oseni
  • 6,086
  • 10
  • 44
  • 69
Jorge L. Morla
  • 630
  • 5
  • 14