0
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.

MaDa
  • 10,016
  • 5
  • 39
  • 81
Secret
  • 27
  • 5

2 Answers2

1
  • hasNextLine() checks to see if there is another linePattern 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.

Community
  • 1
  • 1
Luud van Keulen
  • 1,109
  • 9
  • 34
0

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("*");
    }
  }
} 
Mithilesh Gupta
  • 2,457
  • 1
  • 13
  • 17