home *** CD-ROM | disk | FTP | other *** search
/ Australian Personal Computer 2000 November / APC5112K.ISO / workshop / java / basicinput.java
Encoding:
Java Source  |  2000-07-17  |  1.8 KB  |  95 lines

  1. public class basicinput
  2. {
  3.   public static void main (String args[])
  4.   {
  5.     String s = inString ("Give me a string: ");
  6.     System.out.println ("You typed " + s);
  7.  
  8.     int i = inInt ("Now an int: ");
  9.     System.out.println ("You typed " + i);
  10.  
  11.     char c = inChar ("Now a char: ");
  12.     System.out.println ("You typed " + c);
  13.   }
  14.  
  15.   public static void inputFlush ()
  16.   {
  17.     int dummy;
  18.     int bAvail;
  19.  
  20.     try
  21.     {
  22.       while((System.in.available()) != 0)
  23.         dummy = System.in.read();
  24.      }
  25.      catch(java.io.IOException e)
  26.      {
  27.        System.out.println("Input error");
  28.      }
  29.   } 
  30.  
  31.   public static void printPrompt (String prompt)
  32.   {
  33.     System.out.print (prompt);
  34.   }
  35.  
  36.   public static char inChar (String prompt)
  37.   {
  38.     int aChar = 0;
  39.  
  40.     inputFlush ();
  41.     printPrompt (prompt);
  42.  
  43.     try
  44.     {
  45.       aChar = System.in.read();
  46.     }
  47.     
  48.     catch(java.io.IOException e)
  49.     {
  50.       System.out.println("Input error");
  51.     }
  52.  
  53.     inputFlush();
  54.     return (char) aChar;
  55.   }
  56.  
  57.   public static String inString (String prompt)
  58.   {
  59.     int aChar;
  60.     String s = "";
  61.     boolean finished = false;
  62.  
  63.     printPrompt (prompt);
  64.    
  65.     while(!finished)
  66.     {
  67.       try
  68.       {
  69.         aChar = System.in.read();
  70.         if (aChar < 0 || (char)aChar == '\n')
  71.           finished = true;
  72.         else if ((char)aChar != '\r')
  73.           s = s + (char) aChar;
  74.       }
  75.  
  76.       catch(java.io.IOException e)
  77.       {
  78.         System.out.println("Input error");
  79.         finished = true;
  80.       }
  81.     }
  82.     return s;
  83.   }
  84.  
  85.   public static int inInt (String prompt)
  86.   {
  87.     return Integer.valueOf (inString(prompt).trim()).intValue();  
  88.   }
  89.  
  90.   public static double inDouble (String prompt)
  91.   {
  92.     return Double.valueOf (inString(prompt).trim()).doubleValue(); 
  93.   }
  94. }
  95.