Home > Net >  unable to understand why my throw/catch output is not working
unable to understand why my throw/catch output is not working

Time:11-21

I am just learning about try, and catch in Java. Since the second input in one of the expected outputs is a string and not a number an error is expected. It is expecting this output:

Lee 19 Lua 22 Mary 0 Stu 34

The input is:

Lee 18 Lua 21 Mary Beth 19 Stu 33

So when I try run my code I actually get:

Lee 19 Lua 22 Mary 0 Beth 20 Stu 34

My code:

package study3;

import java.util.Scanner;
import java.util.InputMismatchException;

public class NameAgeChecker {
   public static void main(String[] args) {
      Scanner scnr = new Scanner(System.in);

      String inputName;
      int age = 0;
      
      
      
      inputName = scnr.next();
      while (!inputName.equals("-1")) {
         // FIXME: The following line will throw an InputMismatchException.
         //        Insert a try/catch statement to catch the exception.
          try {age = scnr.nextInt();
         
         }
         
         catch (InputMismatchException expct) {
             
             age = -1; 
              
         }
         System.out.println(inputName   " "   (age   1));
         
         inputName = scnr.next();
      }
   }
}

CodePudding user response:

When an exception occurs, you need to "eat" the wrong input, so add scnr.next() in your catch block.

            try {age = scnr.nextInt();
            }

            catch (InputMismatchException expct) {
                age = -1;
                scnr.next();
            }
  •  Tags:  
  • java
  • Related