-3

i want to read lines in a file as paragraph. for example if there are lines of text without empty space between them it should treat it as 1 paragraph and then i want to count the words.

So far it count the words correctly but doesn't recognise lines of text as a paragraph. Java beginner

Scanner file = new Scanner(new FileInputStream("/.../output.txt"));

int count = 0;

while (file.hasNextLine()) {
    String s = file.nextLine();

    count++;

    if(s.contains("#AVFC")){
        System.out.printf("There are %d words on this line ", s.split("\\s").length-1);
        System.out.println(count);
    }
}

file.close();
Alex Wittig
  • 2,800
  • 1
  • 33
  • 42
JD14
  • 39
  • 1
  • 7
  • http://stackoverflow.com/questions/1706775/java-regex-regular-expression-to-split-a-paragraph-with-start-and-end - possible duplicate. – Gorbles Mar 10 '14 at 15:33

1 Answers1

1

If a "paragraph" is defined as "a sequence of non-blank lines", then do as you're doing for individual lines, but add them up until you get to a blank line (or the end of the file), at which point you have your count for the just completed paragraph. Remember to reset the sum when you finish a paragraph, to get ready for the start of the next one. And you might need to deal with multiple blank lines in a row.

Update: Instead of printing out the number of words in a line, save that number to a variable, say wordsInLine. If that is 0, then you're done with a paragraph (unless count is 0, which means you haven't started a paragraph yet) -- so print your count and reset it.. If not, it is part of the current paragraph, so add it to count. Finally, once you've finished the file, if count isn't 0, you have to print the count of the last paragraph.

Scott Hunter
  • 48,888
  • 12
  • 60
  • 101
  • possible to show this in code?. I'm not sure how this works as I'm fairly new to java – JD14 Mar 10 '14 at 16:04