Scanner error with nextInt()

spatara picture spatara · Oct 11, 2012 · Viewed 52.6k times · Source

I am trying to use Scanner to get an int from the keyboard, but I getting the following error:

Exception in thread "main" java.util.NoSuchElementException
    at java.util.Scanner.throwFor(Scanner.java:907)
    at java.util.Scanner.next(Scanner.java:1530)
    at java.util.Scanner.nextInt(Scanner.java:2160)
    at java.util.Scanner.nextInt(Scanner.java:2119)
    at TableReader.mainMenu(TableReader.java:122)
    at TableReader.main(TableReader.java:76)

This is what I have. It is independent of the rest of my program, I don't understand why this isn't working. It is declared in a method that is being called in a while loop, if that helps.

    // scan for selection
    Scanner s = new Scanner(System.in);
    int choice = s.nextInt();           // error occurs at this line
    s.close();

I stepped through with the debugger and narrowed the error down to:

A fatal error has been detected by the Java Runtime Environment: SIGSEGV (0xb) at pc=0xb6bdc8a8, pid=5587, tid=1828186944

JRE version: 7.0_07-b30 Java VM: OpenJDK Server VM (23.2-b09 mixed mode linux-x86 ) Problematic frame: V [libjvm.so+0x4258a8] java_lang_String::utf8_length(oopDesc*)+0x58

Failed to write core dump. Core dumps have been disabled. To enable core dumping, try "ulimit -c unlimited" before starting Java again

Answer

Hunter McMillen picture Hunter McMillen · Oct 11, 2012

You should use the hasNextXXXX() methods from the Scanner class to make sure that there is an integer ready to be read.

The problem is you are called nextInt() which reads the next integer from the stream that the Scanner object points to, if there is no integer there to read (i.e. if the input is exhausted then you will see that NoSuchElementException)

From the JavaDocs, the nextInt() method will throw these exceptions under these conditions:

  • InputMismatchException - if the next token does not match the Integer regular expression, or is out of range
  • NoSuchElementException - if input is exhausted
  • IllegalStateException - if this scanner is closed

You can fix this easily using the hasNextInt() method:

Scanner s = new Scanner(System.in);
int choice = 0;

if(s.hasNextInt()) 
{
   choice = s.nextInt();
}

s.close();