1
votes

I have a method that a wrote. This method just scans for a user entered integer input. If the user enters a character value it will throw an input mismatch exception, which is handled in my Try-Catch statement. The problem is that, if the user inputs anything that is not a number, and then an exception is thrown, I need the method to loop back around to ask the user for input again. To my understanding, a Try catch statement automatically loops back to the Try block if an error is caught. Is this not correct? Please advise.

Here is my method (it's pretty simple):

public static int getMask() {
        //Prompt user to enter integer mask
        Scanner keyboard = new Scanner(System.in);
        int output = 0;
        try{
            System.out.print("Enter the encryption mask: ");
            output = keyboard.nextInt();
        }
        catch(Exception e){
            System.out.println("Please enter a number, mask must be numeric");
        }
        return output;
    }//end of getMask method

Here is how the method is implemented into my program:

//get integer mask from user input
        int mask = getMask();
        System.out.println("TEMP mask Value is: " + mask);

/***********************************/ Here is my updated code. It creates an infinate loop that I can't escape. I don't understand why I am struggling with this so much. Please help.

public static int getMask() {
    //Prompt user to enter integer mask
    Scanner keyboard = new Scanner(System.in);
    int output = 0;
    boolean validInput = true;

    do{
    try {
        System.out.print("Enter the encryption mask: ");
        output = keyboard.nextInt();
        validInput = true;
    }
    catch(InputMismatchException e){
        System.out.println("Please enter a number, mask must be numeric");
        validInput = false;
        }
    }while(!(validInput));

    return output;

/********************/FINAL_ANSWER I was able to get it finally. I think I just need to study boolean logic more. Sometimes it makes my head spin. Implementing the loop with an integer test worked fine. My own user error I suppose. Here is my final code working correctly with better exception handling. Let me know in the comments if you have any criticisms.

//get integer mask from user input
        int repeat = 1;
        int mask = 0;
        do{
            try{

        mask = getMask();
        repeat = 1;
            }
            catch(InputMismatchException e){
                repeat = 0;
            }
        }while(repeat==0);
3
The try block. No, it does not loop back.Sotirios Delimanolis
Thanks I have read it but I am obviously missing a core conceptuser2993456
So I need a do-while loop then. Well that makes sense. I was just confused about how try-catch blocks work. Thanks.user2993456

3 Answers

2
votes

To my understanding, a Try catch statement automatically loops back to the Try block if an error is caught. Is this not correct?

No this is not correct, and I'm curious as to how you arrived at that understanding.

You have a few options. For example (this will not work as-is but let's talk about error handling first, then read below):

// Code for illustrative purposes but see comments on nextInt() below; this
// is not a working example as-is.
int output = 0;
while (true) {
    try{
        System.out.print("Enter the encryption mask: ");
        output = keyboard.nextInt();
        break;
    }
    catch(Exception e){
        System.out.println("Please enter a number, mask must be numeric");
    }
}

Among others; your choice of option usually depends on your preferred tastes (e.g. fge's answer is the same idea but slightly different), but in most cases is a direct reflection of what you are trying to do: "Keep asking until the user enters a valid number."

Note also, like fge mentioned, you should generally catch the tightest exception possible that you are prepared to handle. nextInt() throws a few different exceptions but your interest is specifically in an InputMismatchException. You are not prepared to handle, e.g., an IllegalStateException -- not to mention that it will make debugging/testing difficult if unexpected exceptions are thrown but your program pretends they are simply related to invalid input (and thus never notifies you that a different problem occurred).

Now, that said, Scanner.nextInt() has another issue here, where the token is left on the stream if it cannot be parsed as an integer. This will leave you stuck in a loop if you don't take that token off the stream. To that end you actually want to use either next() or nextLine(), so that the token is always consumed no matter what; then you can parse with Integer.parseInt(), e.g.:

int output = 0;
while (true) {
    try{
        System.out.print("Enter the encryption mask: ");
        String response = keyboard.next(); // or nextLine(), depending on requirements
        output = Integer.parseInt(response);
        break;
    }
    catch(NumberFormatException e){ // <- note specific exception type
        System.out.println("Please enter a number, mask must be numeric");
    }
}

Note that this still directly reflects what you want to do: "Keep asking until the user enters a valid number, but consume the input no matter what they enter."

1
votes

To my understanding, a Try catch statement automatically loops back to the Try block if an error is caught. Is this not correct?

It is indeed not correct. A try block will be executed only once.

You can use this to "work around" it (although JasonC's answer is more solid -- go with that):

boolean validInput = false;

while (!validInput) {
    try {
        System.out.print("Enter the encryption mask: ");
        output = keyboard.nextInt();
        validInput = true;
    }
    catch(Exception e) {
        keyboard.nextLine(); // swallow token!
        System.out.println("Please enter a number, mask must be numeric");
    }
}
return output;

Further note: you should NOT be catching Exception but a more specific exception class.

0
votes

As stated in the comments, try-catch -blocks don't loop. Use a for or while if you want looping.