Validating User Input in Java Program

(Validating User Input) Modify the program in Fig. 4.12 to validate its inputs. For any input, if the value entered is other than 1 or 2, keep looping until the user enters a correct value.

Validating User Input in Java Program

import java.util.Scanner;
import java.util.InputMismatchException;
public class Scan
{   
	// create function readint for reading input value.
	public static int readInt(String msg)
	{ 
		boolean error=false;
		int x=0;
		do
		{
			try
			{
				// create object of scanner class.
				Scanner KB=new Scanner(System.in);

				// enter here.
				System.out.print("Enter integer : ");
				x=KB.nextInt();
				error=false;
			}
			catch(InputMismatchException e)
			{
				// accept integer only.
				System.out.println("Invalid Input..Pls Input Integer Only..");
				error=true;
			}
		}
		while(error);
		return(x);
	}
}