Input validation

import java.io.*;
public class InputValidation {

	private static BufferedReader  stdIn = new
		BufferedReader(new  InputStreamReader(System.in));

	private static PrintWriter  stdErr = new
		PrintWriter(System.err, true);

	public static int  readInt(int  lo, int  hi) throws IOException  {
		int  x; 
 		do  {
			try  {
				stdErr.print("Enter integer:  ");
				stdErr.flush();

				x = Integer.parseInt(stdIn.readLine());

				if (x >= lo && x <= hi)  {
					break;
				}
			} catch (NumberFormatException  nfe)  {
				stdErr.println(nfe.toString());
			}
		}  while (true);

		return  x;
	}

        public static void main(String[] args) throws IOException {
               int a = Integer.parseInt(args[0]);
               int b = Integer.parseInt(args[1]);
               System.out.println(readInt(a,b) + " in the range of " + a +  " to " + b);
        }
}

Previou page Next page