Question
How is it that for a scanner object the hasNextLine()
method returns true while the hasNext()
method returns false?
Note: Based on the input file, the hasNext()
method is returning the result as expected; the hasNextLine()
does not seem to be returning the correct result.
Code
Here's the code I'm running that's creating the results below:
public void ScannerTest(Reader fileReaderObject){
Scanner scannerObj = new Scanner(fileReaderObject);
for(int i = 1; scannerObj.hasNext(); i++){
System.out.println(i + ": " + scannerObj.next());
System.out.println("Has next line: " + scannerObj.hasNextLine());
System.out.println("Has next: " + scannerObj.hasNext());
}
System.out.println();
scannerObj.close();
}
Input File
The following is the actual content of the file that I'm passing to this scanner:
a 3 9
b 3 6
c 3 3
d 2 8
e 2 5
f 2 2
g 1 7
h 1 4
i 1 1
Result
The following is the end of what's printed in the console when I run my code, and includes the portion I can't make sense of:
25: i
Has next line: true
Has next: true
26: 1
Has next line: true
Has next: true
27: 1
Has next line: true
Has next: false
hasNextLine()
returns true if there is a next line, even empty.hasNext()
returns true if there is one more token. An empty line is a line, which doesn't contain any token.next
doesn't consume the\n
, so the "cursor" is right before the newline, thus there is a next line, but there's no more token.