Java - looping in try-catch block

java

Solution

Avoid using exceptions for flow control. Catch the exception, but only print a message. Also, do need for loops within loops.

It's as simple as this:

public void _____ throws IOException {
    int number = -1;
    while (number == -1) {
        try {
            // Prompt user for line number
            // Getting number from keyboard, which could throw an exception
            number = <get from input>;
        } catch (InputMismatchException e) {
             System.out.println("That is not a number!");
        }  
    }
    // Do something with number
}

Problem

I am working on writing a file reader, and the idea is to have the user enter a number that represents the line number from the text file. The variable that holds this number is of type `int`. However, when the user enters a `String` instead, Java throws the `InputMismatchException` exception, and what I want is to have a loop in the `catch` clause, where I will be looping until the user enters a valid value, i.e. an `int`. The skeleton looks like this: ``` public void _____ throws IOException { try { // Prompting user for line number // Getting number from keyboard // Do something with number } catch (InputMismatchException e) { // I want to loop until the user enters a valid input // When the above step is achieved, I am invoking another method here } } ``` My question is, what are some possible techniques that could do the validation? Thank you.

Original source

Related problems