Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java - looping in try-catch block

Tags:

java

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.

like image 374
chauduyphanvu Avatar asked Jan 16 '23 19:01

chauduyphanvu


1 Answers

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 
       } 
   } 
like image 87
Aram Arabyan Avatar answered Jan 25 '23 15:01

Aram Arabyan