Need a method to validate Scanner input to be between 2 and
Need a method to validate Scanner input to be between 2 and 5. Otherwise ignore the value (meaning ignore non int value, and int value less than 2 and more than 5) need to use \"do while\" and \"try catch\"
Solution
import java.util.Scanner;
 public class ScannerTest {
   
    public static void main(String args[]){
        Scanner scan= new Scanner(System.in);// scan to read input from the user
        boolean shouldContinue=true; // boolean to decide whether to continue or not
        // do-while loop for infinte input
        do{
            try{
                int num=Integer.parseInt(scan.next());// reading integer from the input. throws Number format exception if not an integer
                // if the input is less than 2
                if(num<2){
                    System.out.println(\"Input is less than 2..ignoring\");
                    shouldContinue=false;
                }
                //if the input is greater than 2
                else if(num>5){
                    System.out.println(\"Input is greater than 5..ignoring\");
                    shouldContinue=false;
                }
            }
            // if the input is not of int type then catch block will catch it
            catch(NumberFormatException e){
                System.out.println(\"Input is not an integer..ignoring\");
                shouldContinue=false;
            }
        }while(shouldContinue);
    }
   
 }
--------------------------------------output------------------------------------
7
 Input is greater than 5..ignoring
-10
 Input is less than 2..ignoring
string
 Input is not an integer..ignoring
3
 4
 5
 6
 Input is greater than 5..ignoring
-------------------------output ends-----------------------
NOte: Comments are there to help you in each line. Feel free to ask any question. God bless you!

