Scanner error with nextInt() [duplicate]

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();

Leave a Comment