Cannot Figure out how to catch InputMismatchException

前端 未结 2 2036
一整个雨季
一整个雨季 2021-01-26 12:23

So here is my current code for catching an InputMismatchException error

int weapon = 0
   boolean selection = true;
   while(selection) {
    try {
      System.         


        
2条回答
  •  北荒
    北荒 (楼主)
    2021-01-26 13:04

    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();
        }
    }
    

提交回复
热议问题