-1

I need to read a text file only once and store the sentences into an ArrayList. Then, I need to split the ArrayList of sentences into another ArrayList of each individual word. Not sure how to go about doing this?

In my code, I've split all the words into an ArrayList, but I think it's reading from the file again, which I can't do.

My code so far:

public class Main {
    public static void main(String[] args){
        try{
            FileReader fr = new FileReader("input.txt");
            BufferedReader br = new BufferedReader(fr);
            ArrayList<String> sentences = new ArrayList<String>();
            ArrayList<String> words = new ArrayList<String>();

            String line;
            while((line=br.readLine()) != null){
                String[] lines = line.toLowerCase().split("\\n|[.?!]\\s*");
                for (String split_sentences : lines){
                    sentences.add(split_sentences);
                }
               /*Not sure if the code below reads the file again. If it
                 does, then it is useless.*/
                String[] each_word = line.toLowerCase().split("\\n|[.?!]\\s*|\\s");
                for(String split_words : each_word){
                    words.add(split_words);
                }
            }
            fr.close();
            br.close();

            String[] sentenceArray = sentences.toArray(new String[sentences.size()]);
            String[] wordArray = words.toArray(new String[words.size()]);  
         }
         catch(IOException e) {
         e.printStackTrace();
        }
    }
}
  • 1
    You're reading the file only once. Why do you think you are reading it more than once? – Nicholas K Sep 02 '18 at 06:34
  • What exactly do you mean? `readLine()` does not mean that you read the whole file. – dim Sep 02 '18 at 06:42
  • If you want to read the whole file at once maybe you should see [this post](https://stackoverflow.com/questions/3849692/whole-text-file-to-a-string-in-java). [This](https://stackoverflow.com/a/14169760/2595579) can be also useful. – dim Sep 02 '18 at 06:52
  • Thanks for the links, dim. The instructions make it seem like if you loop through the file, it reads it again. I wasn't sure if each for loop was rereading the file. – StormRider42 Sep 02 '18 at 07:15

1 Answers1

0

/*Not sure if the code below reads the file again. If it does, then it is useless.*/

It doesn't. You are simply reparsing the line that you have already read.

You have already solved your problem.

Stephen C
  • 698,415
  • 94
  • 811
  • 1,216