Reputation: 27
for(int i = 0 ; i < 10 ; i++)
{
out.println(9);
}
out.close();
while (s.hasNextLine()) {
int i = s.nextInt();
if ( i == 9);
{
System.out.print("*");
}
}
s.close();
It still prints out 10 "*", but i get this error afterward:
**********java.util.NoSuchElementException
at java.util.Scanner.throwFor(Unknown Source)
at java.util.Scanner.next(Unknown Source)
at java.util.Scanner.nextInt(Unknown Source)
at java.util.Scanner.nextInt(Unknown Source)
at insertionSort.main(insertionSort.java:18)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at edu.rice.cs.drjava.model.compiler.JavacCompiler.runCommand(JavacCompiler.java:272)
But if I use hasNext instead of hasNextLine, it works fine.
So I am wondering why hasNext works, but hasNextLine doesn't.
Upvotes: 0
Views: 169
Reputation: 1254
hasNextLine()
checks to see if there is anotherlinePattern
in the buffer.hasNext()
checks to see if there is a parseable token in the buffer, as separated by the scanner's delimiter.Since the scanner's delimiter is whitespace, and the linePattern is also white space, it is possible for there to be a linePattern in the buffer but no parseable tokens.
Source: https://stackoverflow.com/a/31993534/5333805
So your file could have an empty newline so you try to read a character which isn't there.
Upvotes: 1
Reputation: 2930
You should check for nextInt before trying to get it:
while (s.hasNextLine()) {
if(s.hasNextInt()){
int i = s.nextInt();
if ( i == 9);
{
System.out.print("*");
}
}
}
Upvotes: 0