How do I keep a scanner from throwing exceptions when the wrong type is entered? (java)

Posted by David on Stack Overflow See other posts from Stack Overflow or by David
Published on 2010-03-22T22:31:07Z Indexed on 2010/03/22 22:41 UTC
Read the original article Hit count: 286

Filed under:
|

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 4then everything goes fine.

if, on the other hand, 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 so that i can make it so that it either ignores entries that aren't ints or re prompts with "how many are invading?"? i'd like to know how to do both of these.

© Stack Overflow or respective owner

Related posts about java

Related posts about text-parsing