Search code examples
javaexceptiontry-catchinputmismatchexception

Cannot Figure out how to catch InputMismatchException


So here is my current code for catching an InputMismatchException error

int weapon = 0
   boolean selection = true;
   while(selection) {
    try {
      System.out.println("Pick number 1, 2, or 3.");
      weapon = scan.nextInt(); 
      selection = false;
    } catch(InputMismatchException e) {
        System.out.println("Choose 1,2,3");
        weapon = scan.nextInt();
      }
   }

I'm trying to make sure that an int is entered and not anything else. Scanner class as already been implemented and 'scan' will act as it for me.

Thanks for any efforts to help!


Solution

  • Try this:

    int weapon = 0;
       do{
           System.out.println("Pick number 1, 2, or 3.");
           if(scan.hasNextInt()){
               weapon = scan.nextInt();
               break;
           }else{
               System.out.println("Enter an integer only");
               scan.nextLine();
           }
       }while(true);
    

    This will make sure it is an integer and it will keep asking until it gets it.