4

I have a question, I tried to create an app that counts all occurences of a symbol in a file... The scanner method "nextLine" stops at an empty line... Is there a way to keep it going until it reaches the real end of the file?

In short: can I get the REAL number of lines in a file?

Thankyou in advance!

Justas S
  • 584
  • 4
  • 12
  • 34
  • 4
    It doesn't stop until you reach the end of the file. Can you show us code to reproduce this? – Peter Lawrey Sep 19 '13 at 18:54
  • I believe I have the same dilemma. If that's so, the issue is that if the last line is blank, the counter will not count that last line and give a line count one less than actual. – Daniel B. Nov 05 '13 at 02:18

3 Answers3

8

You can use a loop:

int count = 0;
while (scanner.hasNextLine()) {
    count++;
    scanner.nextLine();
}

count will contain number of lines.

Guillaume Poussel
  • 9,572
  • 2
  • 33
  • 42
Eugen Halca
  • 1,775
  • 2
  • 13
  • 26
  • 1
    don't forget to use scanner.nextLine(); or you will have an infinite loop. –  Feb 02 '16 at 05:35
1

So I've been doing some research about this problem. I've been coming up against it recently while writing a line counting program in Java for the class I'm taking.

The reason the scanner class does this is because scanner.next() and scanner.nextLine() return tokens, which are separated by delimiters. By default the delimiter is whitespace. So what's happening is that when you call scanner.hasNext() or scanner.hasNextLine() is that it looks to see if there is a token after the next delimiter. When a file ends in a newline character, there is no token after that, so hasNext() and hasNextLine() return false.

As far as I can tell, to do what you want you'd need to count the number of delimiters, which is better handled in Martinus's answer. See also AFinkelstein's answer.

Community
  • 1
  • 1
wolf123450
  • 103
  • 1
  • 7
0

See Scanner.hasNextLine(), you should probably use that in the loop condition. There is also a Scanner.hasNext() if it works better for your needs.

dajavax
  • 3,060
  • 1
  • 14
  • 14