0

Im taking input from a separate file which currently has one paragraph. Im storing every word in the paragraph into a list and then iterating over each of them using this:

for (String word: words)

However, this iterator goes over each WORD. If I have two paragraphs in my input file which are separated by an empty line, how do I recognize that empty line under this for-loop iterator? My thinking is that iterating over words is obviously different from going over lines, so Im not sure.

AayushK
  • 73
  • 3
  • 10
  • 1
    Is it possible for you to only deal with a paragraph at a time? If so, you could just read up to the empty line, deal with that paragraph, then read in the second paragraph *after* you're done with the first. – Dennis Meng Oct 09 '13 at 22:07
  • You act surprised that the iterator goes over each word, yet that is specifically what you've told it to do. Can you give a more complete example of your code? – vincentvanjoe Oct 09 '13 at 22:12

1 Answers1

0

An empty line follows the pattern:

\n\n       
\r\n\r\n
\n -whitespace- \n 
etc

A word following the pattern

-whitespace-nonwhitespace-whitespace- 

Very different patterns. So looping over something using the definition of a word will never work.

You can use Java scanner to look at a file line by line.

public class LineScanner {

  public List<String> eliminateEmptyLines(String input) {
    scanner Scanner = new Scanner(input);
    ArrayList<String> output = new ArrayList<>();
    while (scanner.hasNextLine) {
      String line = scanner.nextLine;
      boolean isEmpty = line.matches("^\s*$"); 
      if !(isEmpty) {
        output.add(line);
      }
    }
    return output;
  }
}

Here's how the regex in String.matches works: How to check if a line is blank using regex
Here's the javadoc on Scanner: http://docs.oracle.com/javase/1.5.0/docs/api/java/util/Scanner.html

Community
  • 1
  • 1
Johan
  • 74,508
  • 24
  • 191
  • 319