0

I have an ArrayList of String Arrays. The arrays themselves should be holding every word of text files passed in. Then, the arrays are stored in an index of the ArrayList. For some reason, it's not working. It's only storing one word per array. What I'm trying to accomplish is when I call for a index of the ArrayList, it should print out all the words from the text file that was stored in the array. Can someone please look at this and point me in the right direction? I really appreciate any feedback. Thank you in advance.

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Scanner;

public class Main {
    public static void main(String[] args) throws IOException{
        String [] files = {"C:\\Users\\Kelvin\\Documents\\Hello.txt", "C:\\Users\\Kelvin\\Documents\\Mountain.txt", "C:\\Users\\Kelvin\\Documents\\Thanks.txt"};
        ArrayList<String[]> list =  new ArrayList<String[]>();
        BufferedReader reader;

        for(int i = 0; i < files.length; i++){
            reader = new BufferedReader(new FileReader(files[i]));
            Scanner in = new Scanner(reader.readLine());
            String [] words = null;
            while(in.hasNext()){
                String inputText = in.next();
                words = inputText.split("[ \n\t\r,.;:!?*--+(){}}]");
            }
            in.close();
            list.add(words);
        }
        System.out.println(Arrays.deepToString(list.toArray()));
    }
}
5
  • You will have to add each of the word after the split. Commented Apr 4, 2017 at 17:13
  • 1
    That's what debuggers were made for Commented Apr 4, 2017 at 17:13
  • Try in.nextLine() instead of in.next(). Commented Apr 4, 2017 at 17:15
  • Move list.add(words); inside the while loop after words = inputText... statement. Commented Apr 4, 2017 at 17:16
  • Please keep the list.add(words); in while loop. Commented Apr 4, 2017 at 17:18

1 Answer 1

1

You are missing this part here :

while (in.hasNext()) {
    String inputText = in.nextLine();//<----nextLine instead of next
    words = inputText.split("[ \n\t\r,.;:!?*--+(){}}]");
    list.add(words);//<----------Add your result to your List
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.