Gprice1148
Gprice1148

Reputation: 19

Read in a text file 1 line at a time and split the words into an Array Java

The user selects a text file. I take the file and split 1 line into individual words. I then take an if statement to see if one of the words is equal to the word "the". There is the word "the" in the first line however it's not saying there is.IT IS picking up other "the"s just not the very first one (yes I know this is a mess, but it's what I'm working with at the moment)

try {
    BufferedReader br = new BufferedReader(new FileReader(test));
    //String text = "";
    String line = br.readLine();

    //while (line != null)
    if(line != null) {
        for(int j = 0; j < 20; j++) //loops through first 20 lines {
            if(line != null) {
                //text += line;
                String[] words = line.toLowerCase().split(" ");
                for(int i = 0; i < words.length; i++){//loops array of split up words
                    if(words[i].equals("the")) {
                        System.out.println("Found T H E");
                    } else {
                        System.out.println("Didn't find the");
                        System.out.println(words[i]);
                    }
                    line = br.readLine(); 
                }
            } else {
                System.out.println("");
            }
        }
    } else {
        System.out.println("It's null");
    }
    br.close();
} catch (Exception ex) {
    System.err.println("Error" + ex);
}

Upvotes: 0

Views: 50

Answers (1)

Clauds
Clauds

Reputation: 950

Try moving the line

line = br.readLine(); 

outside of the loop

for(int i = 0; i < words.length; i++){

Upvotes: 2

Related Questions