Results 1 to 3 of 3
  1. #1
    DMarsh12 is offline Member
    Join Date
    Mar 2011
    Posts
    43
    Rep Power
    0

    Default How to handle InputMismatchException

    I am writing a code that I want only to accept numbers 1 through 8 and to recognize when it isn't an integer being put in. I tried the following:

    Java Code:
    		int classSelect = keyboard.nextInt();
    		
    		try
    		{
    		while( (classSelect<1 || classSelect>8))
    			{
    				System.out.println("You must pick between one and eight.  Please enter again");
    				classSelect=keyboard.nextInt();
    			}
    		
    		}
    		catch (Exception e)
    		{
    			System.out.println("Error");
    		}
    I looked at the API and I looked all over the internet and can't grasp what I am doing wrong. I keep getting this error:

    Exception in thread "main" java.util.InputMismatchException
    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 input.classSelect(input.java:30)
    at input.readVisitor(input.java:17)
    at main.main(main.java:15)

    Any help would be greatly appreciated

  2. #2
    Junky's Avatar
    Junky is offline Grand Poobah
    Join Date
    Jan 2011
    Location
    Dystopia
    Posts
    3,798
    Rep Power
    7

    Default Re: How to handle InputMismatchException

    InputMismatchException is thrown when you attempt to read data of one type when in fact it is a different type eg: attempting to read a String as an int. This is a runtime exception (which means it is unchecked) and your code should handle it properly instead of using a try/catch statement. One way would be to read input as a String. Then check to see that it is an int before using parseint. Or use the hasNextInt method.

  3. #3
    superhaNds is offline Senior Member
    Join Date
    Apr 2013
    Location
    Sweden
    Posts
    265
    Rep Power
    2

    Default Re: How to handle InputMismatchException

    you read input two times. The first time it will throw an exception and crash because it is out of the try block.

Similar Threads

  1. InputMismatchException
    By Kartright in forum New To Java
    Replies: 6
    Last Post: 06-04-2013, 04:03 PM
  2. InputMismatchException Error
    By fatihkok in forum New To Java
    Replies: 3
    Last Post: 02-04-2013, 03:41 PM
  3. throw new InputMismatchException
    By Pat in forum New To Java
    Replies: 8
    Last Post: 10-09-2012, 09:53 AM
  4. InputMismatchException
    By gnbradford in forum New To Java
    Replies: 3
    Last Post: 09-22-2012, 09:45 PM
  5. InputMismatchException
    By jihad in forum New To Java
    Replies: 5
    Last Post: 12-17-2011, 03:10 PM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •