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!
You can use a loop:
int count = 0;
while (scanner.hasNextLine()) {
count++;
scanner.nextLine();
}
count
will contain number of lines.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With