-1

To validate for an int input, I've seen the usage of try-catch using the InputMismatch exception. After inputting a string though, I simply get the catch code block played, then my program exits due to mismatch, but instead I want to allow the user to re-enter input. I implemented a boolean correct while loop after searching around but that still didn't do the trick.

        int quantity = 0;
        boolean correct = true;
        while(correct){
            try{
                System.out.print("Input Quantity you would like to purchase: ");//Get quantity
                quantity = input.nextInt();
            }catch(InputMismatchException e){
                System.out.println("Input must be a number");
                input.nextInt();//Get the input as a string
                correct = false;
            }
            System.out.println("Quantity: " + quantity);
        }

I previously just used the Scanner's built in hasNextInt, and that works great, but wanted to test out try-catch. I've heard to use try-catch and not to use try-catch. Why would I avoid using it?

Stealthy
  • 3
  • 1
  • 1
    Filling in a stack trace is expensive. Also, `input.nextInt();//Get the input as a string` doesn't do what the comment says. You want `input.nextLine();//Get the input as a string` – Elliott Frisch Apr 29 '22 at 04:18
  • The correct way to do this with `Scanner` is to test `input.hasNextInt()`, and complain if it doesn't. – user207421 Apr 29 '22 at 04:23
  • See https://softwareengineering.stackexchange.com/questions/189222/are-exceptions-as-control-flow-considered-a-serious-antipattern-if-so-why for detailed discussions on when exceptions should be used. – Hulk Apr 29 '22 at 04:23
  • (for answering the more general question in the last line) – Hulk Apr 29 '22 at 04:24
  • Concerning which, exceptions should be used when they are the best solution, like anything else, and not used when there is a better solution. Mere exception-phobia is irrational and should be ignored. There are circumstances when there is no other choice. – user207421 Apr 29 '22 at 04:29

1 Answers1

0

Here is the fix, use input.nextLine(); in catch and don't make the correct=false

while(correct){
            try{
                System.out.print("Input Quantity you would like to purchase: ");//Get quantity
                quantity = input.nextInt();
            }catch(InputMismatchException e){
                System.out.println("Input must be a number");
                input.nextLine();
                continue;
            }
            System.out.println("Quantity: " + quantity);
        }

But like others pointed out, try not to use Exceptions for general flow. Use it only for tracking unusual exceptions. So, I am discouraging you to use this code. Use, input.hasNextInt() instead

Chetan Ahirrao
  • 1,454
  • 11
  • 16