/*****************************************************************
** InputInteger - demonstrate input validation 
** 
** (c) Scott MacKenzie, 2000                             
******************************************************************/
import java.io.*;

public class InputInteger
{
   public static void main(String[] args) throws IOException
   {
      // setup 'stdin' as handle for keyboard input
      BufferedReader stdin =
         new BufferedReader(new InputStreamReader(System.in), 1);

      // send prompt, get input and check if valid
      String s;
      do
      {
         System.out.print("Enter an integer: ");
         s = stdin.readLine();
      }
      while (!isValidInteger(s));

      // convert string to integer (safely!)
      int i = Integer.parseInt(s);

      // done!
      System.out.println("You entered " + i +  " (Thanks!)");
   }

   // check if string contains a valid integer
   public static boolean isValidInteger(String str)
   {
      // return 'false' if empty string
      if (str.length() == 0)
         return false;

      // skip over minus sign, if present
      int i;
      if (str.indexOf('-') == 0)
         i = 1;
      else
         i = 0;

      // ensure all characters are digits
      while (i < str.length())
      {
         if (!Character.isDigit(str.charAt(i)))
            break;
         i++;
      }

      // if reached the end of the line, all characters are OK!
      if (i == str.length())
         return true;
      else
         return false;
   }
}

