After you call hasNext()
the first time if you don't read from the file hasNext()
will always return true. Because the front of the input doesn't change.
Imagine you have a file with this line in it:
this is input
If you call hasNext()
on this file, it will return true
because there is a next token in the file, in this case the word this
.
If you don't read from the file after this initial call, the "next" input to be processed is STILL the word this
. The next input doesn't change until you read from the file.
TL;DR
When you call hasNext()
read from the file, otherwise you will always have an infinite loop.
Additionally
If you really want to use hasNext()
, or would like to, you could create another Scanner
object and read through the file to count the lines, then your loop would work fine. also, you should really use hasNextLine()
public int countLines(File inFile)
{
int count = 0;
Scanner fileScanner = new Scanner(inFile);
while(fileScanner.hasNextLine()) //if you are trying to count lines
{ //you should use hasNextLine()
fileScanner.nextLine() //advance the inputstream
count++;
}
return count;
}
Hope this is helpful.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…