After calling hasNext()
for the first time, if you do not read from the file hasNext()
will always return true. Since the front of the input is not changed.
Imagine you have a file with this line:
introduced
If you call hasNext()
in this file, it will return true
because the file has the next token, in this case the word this
.
If you do not read the file after this initial call, the βnextβ input to be processed, STILL, is the word this
. The next input does not change until you read from the file.
TL DR
When you call hasNext()
read from a file, otherwise you will always have an infinite loop.
Additionally
If you really want to use hasNext()
or you want, you can create another Scanner
object and read the file to count the lines, then your loop will work fine. Also, you really should use hasNextLine()
public int countLines(File inFile) { int count = 0; Scanner fileScanner = new Scanner(inFile); while(fileScanner.hasNextLine())
Hope this will be helpful.
source share