Alex Rivera | Logout

How do I keep a Scanner from throwing exceptions when the wrong type is entered?

Asked 2010-03-22T22:31:07.610
17

Here's some sample code:

import java.util.Scanner;
class In
{
    public static void main (String[]arg) 
    {
    Scanner in = new Scanner (System.in) ;
    System.out.println ("how many are invading?") ;
    int a = in.nextInt() ; 
    System.out.println (a) ; 
    } 
}

If I run the program and give it an int like 4, then everything goes fine.

On the other hand, if I answer too many it doesn't laugh at my funny joke. Instead I get this(as expected):

Exception in thread "main" java.util.InputMismatchException
    at java.util.Scanner.throwFor(Scanner.java:819)
    at java.util.Scanner.next(Scanner.java:1431)
    at java.util.Scanner.nextInt(Scanner.java:2040)
    at java.util.Scanner.nextInt(Scanner.java:2000)
    at In.main(In.java:9)

Is there a way to make it ignore entries that aren't ints or re prompt with "How many are invading?" I'd like to know how to do both of these.

Edit
Report

1 Answer

1

It's always a benefit to have your application throw an error when an error occurs opposed to ways to keep it from happening.

One alternative is to wrap the code inside a try {...} catch {...} block for InputMismatchException. You might also want to wrap the code inside a while loop to have the Scanner keep prompting until a specific condition is met.

answered 2010-03-22T22:33:59.047

Your Answer