-1

How can I solve it ???

Why the second catch keeps printing in the output console ...

I just mean to print it once and then get back to the loop again if the boolean data type is not true .

    Scanner input=new Scanner(System.in);

    int a ,b,result;
    boolean status=false;
    while(!status){
    try{

        a=input.nextInt();
        b=input.nextInt();

        result=a/b;
        status=true;

    }catch (ArithmeticException ex){

        System.out.println(ex.getMessage());

    }catch(InputMismatchException ex){

        System.out.println(ex);

    }catch(Exception ex){

        System.out.println(ex.getMessage());

    }
    }

}
MHM
  • 3
  • 4

2 Answers2

0

please check my in line comments

while(!status){
    try{

        a=input.nextInt();
        b=input.nextInt();

        result=a/b;
        status=true;

    }catch (ArithmeticException ex){

        System.out.println(ex.getMessage());

    }catch(InputMismatchException ex){

        System.out.println(ex);
        input.next(); // So when ever InputMismatchException occurs Scanner will not consume the token it will keep that token so we need to consume that by using `next()`
    }catch(Exception ex){

        System.out.println(ex.getMessage());

    }
prasad
  • 1,277
  • 2
  • 16
  • 39
  • This works better as he need to get input from scanner infinite time but in your code also it keeps exiting after your give valid inputs ... loop still exits. i assume he is trying to get input from user infinite time – Rocket_03 Aug 25 '18 at 06:53
0

Add break statement inside catch block which you are using to get all the mismatch inputs

catch(InputMismatchException ex){
            ex.printStackTrace();
            System.out.println(ex.getMessage());
            break;
        }
Rocket_03
  • 45
  • 8