0

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!

Syrobot
  • 3
  • 1
  • Yes I have looked at many other questions concerning the same thing and haven't been able to figure it out. – Syrobot Apr 23 '15 at 00:24
  • It's not clear what your question is. What are you expecting this to do? And more importantly, what **is** it doing? Providing output of a run would help. – Mike Ounsworth Apr 23 '15 at 00:30

2 Answers2

0

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.

Forseth11
  • 1,418
  • 1
  • 12
  • 21
0

In the first place, you already have a loop with which to prompt for and scan the desired int. You do not need to duplicate that behavior in your exception handler. What you do need to do, however, is discard the mismatching token from the scanner in order to allow a new one to be scanned.

As a secondary matter, your selection variable appears to be redundant.

It looks like this might do what you're after:

int weapon = 0
while(weapon < 1 || weapon > 3) {
    try {
        System.out.println("Pick number 1, 2, or 3.");
        weapon = scan.nextInt(); 
    } catch(InputMismatchException e) {
        //discard the mismatching token
        scan.next();
    }
}
John Bollinger
  • 160,171
  • 8
  • 81
  • 157
  • Yea I had previously done something like this before, but it didn't work out. Now I see the differences and how that way could have worked. Thanks for the tip about the while loop, will be helpful! – Syrobot Apr 23 '15 at 00:45