FileDocCategorySizeDatePackage
InputReader.javaAPI DocExample2851Thu Feb 03 08:18:02 GMT 2000None

InputReader.java

// File: InputReader.java
// T Balls
// Nov 1997
// Demonstrate how to read values from an input stream
// Data will be read from the System.in stream

import java.io.*;
import java.util.*;

public class InputReader
{
   public static void main( String[] args )
   {  System.out.println( "This program will read, and echo some values\n" );

      BufferedReader is = new BufferedReader(
                                new InputStreamReader( System.in ) );
      String instring = null;

      System.out.print( "Please enter a string\n> " );
      try
      {  instring = is.readLine();
      }
      catch( IOException ioe )
      {  ioe.printStackTrace();
         System.exit( -1 );
      }
      System.out.println( "You input: " + instring );

      StringTokenizer st = null;
      String item = null;

      System.out.print( "\nPlease enter an integer\n> " );
      int i = 0;
      while( true )
      {  try
         {  instring = is.readLine();
            st = new StringTokenizer( instring );
            item = st.nextToken();
            i = new Integer( item.trim() ).intValue();
            break;
         }
         catch( IOException ioe ) // from is.readLine()
         {  ioe.printStackTrace();
            System.exit( -1 );
         }
         catch( NoSuchElementException nse ) // from st.nextToken()
         {  nse.printStackTrace();
            System.out.print( "\nPlease enter SOMETHING!\n> " );
         }
         catch( NumberFormatException nfe ) // from Integer constructor
         {  nfe.printStackTrace();
            System.out.print( "\nPlease input an INTEGER!\n> " );
         }       
      } // end while( read an integer )
      System.out.println( "You input : " + i );

      System.out.print( "\nPlease enter a floating point value\n> " );
      double d = 0.0;
      while( true )
      {  try
         {  instring = is.readLine();
            if( instring == null )
            {  throw new NoSuchElementException();
            }
            st = new StringTokenizer( instring );
            item = st.nextToken();
            d = new Double( item.trim() ).doubleValue();
            break;
         }
         catch( IOException ioe )
         {  ioe.printStackTrace();
            System.exit( -1 );
         }
         catch( NoSuchElementException nse )
         {  nse.printStackTrace();
            System.out.print( "\nPlease enter SOMETHING!\n> " );
         }
         catch( NumberFormatException nfe )
         {  nfe.printStackTrace();
            System.out.print( "\nPlease input a FLOAT value!\n> " );
         }
         finally
         {  System.out.println( "*** finally ..." );
         }
      } // end while( mine's a double )
      System.out.println( "You input : " + d );

   }

}