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.
while(true){
try {
// Prompting user for line number
// Getting number from keyboard
// Do something with number
//break;
} 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
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With