how to ask an integer from the user 3 times with try catch block

Viewed 37

the user has to enter 3 integers into a list. im trying to make a try catch block to filer out if the user inputs anything other than an integer.

i inserted the try catch block inside the for loop, the problem is even if the input is not an integer my code scans it and only prints the "enter an integer:" 3 times. how to fix that?

THIS IS MY CODE


for(int i = 0; i<3; i++){
            try{
                //some code
            }catch(Exception e){}
        }

i would like the code to go like this:

if the user enters an integer, they only need to input 2 integers if the user enters a character, the code will prompt an error and will loop back to ask for an integer (2 integers only because the user already entered 1 integer)

enter an integer: 1
enter an integer: z

the input is invalid, please try again.

enter an integer: 2
enter an integer: ac

the input is invalid, please try again.

enter an integer: 3
2 Answers

you can make use of a counter variable, to count valid inputs.

The easiest would be to move the

System.out.println("done! thank you.");

into the try block like that

for(int i = 0; i<3; i++){
            try{
                System.out.print("Enter an integer:");
                user_input[i] = input.nextInt();
                System.out.println("done! thank you.");
            }catch(InputMismatchException e){
                System.out.println("the input is invalid, please try again");
                input.next();
            }
        }

Finally block tries to execute always - no matter how the execution was interrupted. And if you want the user to repeat the the entry, than go i--; in the catch block.

Related