Search code examples
javaexceptiontry-catchjava.util.scannerinputmismatchexception

Java: Getting the Value of the User Input that Threw an Exception


I'm trying to catch an InputMismatchException with the Scanner expecting a double, and if the input is equal to "c" or "q" I want to do run some specific code in the catch block. I'm wondering if there's a way to get the value of the user input after an exception has been thrown. So for example, if the code calls for a double and the user enters the letter "c", I want to be able to know that specifically "c" was input, and do something if true. Here's the code I'm trying to write, where "getValue()" is a made-up method name to describe what I'm trying to accomplish:

double value = 0.0;

try{
    System.out.print("\nEnter a number: ");
    value = input.nextDouble();
}
catch(InputMismatchException notADouble){
    if(notADouble.getValue().equalsIgnoreCase("c")){
        //run the specific code for "c"
    }
    else if(notADouble.getValue().equalsIgnoreCase("q")){
        //run the specific code for "q"
    }
    else{
        System.out.print("\nInvalid Input");
    }
}

Thanks in advance for your input :)


Solution

  • Use Scanner.hasNextDouble() to validate the input before Scanner tries to convert it to a number. Something like this should work:

      double value = 0.0;
    
      Scanner input = new Scanner(System.in);
    
         System.out.print("\nEnter a number: ");
         while(input.hasNext())
         {
            while(input.hasNextDouble())
            {
               value = input.nextDouble();
            }
    
            String next = input.next();
    
            if("c".equals(next))
            {
               //do something
            }
            else if("q".equals(next))
            {
               //do something
            }
            else
            {
               System.out.print("\nInvalid Input");
               //return or throw exception
    
            }
         }