Don't use the Scanner (input
) for more than one thing. You're using it to read lines from a file, and also trying to use it to count words in those lines. Use a second Scanner to process the line itself, or use a different method.
The problem is that the scanner consumes its buffer as it reads it. input.nextLine()
returns sentences
, but after that it no longer has them. Calling input.hasNext()
on it gives you information about the characters after sentences
.
The simplest way to count the words in sentences
is to do:
int wordCount = sentences.split(" ").length;
Using Scanner, you can do:
Scanner scanner = new Scanner(sentences);
while(scanner.hasNext())
{
scanner.next();
wordCount++;
}
Or use a for loop for best performance (as mentioned by BlackPanther).
Another tip I'd give you is how to better name your variables. countWords
should be wordCount
. "Count words" is a command, a verb, while a variable should be a noun. sentences
should simply be line
, unless you know both that the line is composed of sentences and that this fact is relevant to the rest of your code.