UCL Logo

class KeyboardInput
Reading Input from the Keyboard

These notes show how to use a class called KeyboardInput for reading values typed in at the keyboard. The class brings together a collection of useful input methods that you can call from your programs. The class is taken from the text book, where it is used in some of the examples and is listed in Appendix F.

Using the class you can write interactive programs that are able to input values of the following types:

  • int
  • long
  • double
  • float
  • char
  • String

The user of your interactive program has to type a value using the correct format for that type. For example, 123 would be a valid int value but xyz would not be. Reading input is always tricky as you have to deal with all the strange things that someone may type in!

If something is typed in that cannot be recognised as a value of the type being asked for, a default value is returned, rather than an error being reported. For numbers the default is zero, for char a space and for String an empty string.

Using KeyboardInput

To use the KeyboardInput class save the source code, which is listed below, into a file called KeyboardInput.java (you can use copy and paste from the web page version of these notes). Note the way the KeyboardInput is spelt using a capital K and I. You must use the same combination of upper and lower case letters.

Next compile the code to produce the file KeyboardInput.class. This file, or a copy of it, should then be placed in any directory you are using when working on your exercises. (If you want to be more sophisticated and avoid making copies of the .class file investigate how to use the CLASSPATH environment variable, or how to use a programming environment such as Eclipse.)

Note — an interactive program using KeyboardInput must be run from the command line (an xterm window, or a MS Windows Command Prompt window, or a Mac OS X terminal window).  Simply open the appropriate window, change to the correct directory and use the java command (e.g., java MyInteractiveProgram). You can still edit and compile the program using JEdit or BlueJ.

A program that needs to do input first has to create a KeyboardInput object using the KeyboardInput class. Do this by having a line in your program that looks like this:

        KeyboardInput in = new KeyboardInput() ;

This line must appear before you do any input and will give you a variable called in that references a KeyboardInput object. Once you have an object you call its input methods. For example, to input an integer you would use:

int x = in.readInteger() ; 

When this statement is executed, the program will wait for you to type in some input. The input must be ended by pressing the <return> key, otherwise nothing more will happen! Once the input has been read an attempt will be made to recognise the characters that were typed in as an integer of type int. If successful the int value will be returned. If not, then a default value of 0 is returned. The variable x will be initialised accordingly.

To let someone using your program know that input is expected, it is a good idea to print a message asking for the input. For example:

System.out.print("Type a floating point number: ") ;
double d = in.readDouble() ;

Note the use of print, rather than println, so that the input follows the request on the same line.

The following test program shows the use of all the input methods provided by the class. To run this program, save the source code to a file called KeyboardInputTest.java and compile and run it, having first made sure that a copy of KeyboardInput.class is in the same directory.

class KeyboardInputTest
{
  public void runTest()
  {
    KeyboardInput in = new KeyboardInput();
    System.out.print("Type an integer: ");
    int n = in.readInteger();
    System.out.println("Integer was: " + n);
    System.out.print("Type a long: ");
    long l = in.readLong();
    System.out.println("Long was: " + l);
    System.out.print("Type a double: ");
    double d = in.readDouble();
    System.out.println("Double was: " + d);
    System.out.print("Type a float: ");
    float f = in.readFloat();
    System.out.println("float was: " + f);
    System.out.print("Type a char: ");
    char c = in.readCharacter();
    System.out.println("char was: " + c);
    // Note that reading one character leaves the newline
    // character still in the input buffer. Do an extra
    // read to use it up.
    c = in.readCharacter();
    // Newlines are represented using two characters on Microsoft
    // Windows systems, so an further read is needed.
    // c = in.readCharacter() ;
    System.out.print("Type a String: ");
    String s = in.readString();
    System.out.println("String was: " + s);
  }
  public static void main(String[] args)
  {
    KeyboardInputTest inputTest = new KeyboardInputTest();
    inputTest.runTest();
  }
}

Input Buffering

Input from the keyboard is buffered in an input buffer managed by the operating system. This means that all the characters typed are collected up and temporarily stored until the <return> key is pressed. The operating system keeps your program waiting while you are typing, so your program is not actually doing anything. Only after the <return> key is pressed does your program carry on executing. While your program is waiting we say it is suspended or blocked.

As a result of the buffering your program receives a whole line of characters at a time, not single characters one after another. The line of characters includes a newline character at the end — newline is the character generated by pressing <return>. When you read any type of value, except for char, the newline character is automatically removed and you don't see it. However, when you read a character the newline is left in place and you need to do an extra readCharacter to get rid of it. You can see this being done in the test program above, so don't forget to take this into account when reading characters. If you are using a Microsoft Windows system you will find that newlines are represented by two characters, so an extra read is needed to remove all the characters compared to a Unix system.

Note that due to buffering, calling readCharacter may simply return the next character in the buffer if one is available because the user has typed in several characters (even if only asked for one). In this case, there is no need for the program to wait for anything more to be typed in. If programs using readCharacter appear not to wait for input, then check for this situation as well as taking the newline characters into account.

The KeyboardInput class code listing follows. The class uses a number of Java features that are not covered in 1B1a or 1B1b, along with several library classes. At this stage an understanding of how the class works is not needed but it is well worth the challenge of looking through it and trying to work out what all the code does. Use the text book to help. Also, note the way the class has been commented. It has actually been fully commented using documentation comments, which can be automatically processed to produce online documentation in the form of web pages.

import java.io.*;
/**
 *  A simple input class to read values typed at the command line. If an error
 *  occurs during input, any exceptions thrown are caught and a default value
 *  returned.
 * 
 * @author     Graham Roberts
 * @author     Russel Winder
 * @version    1.2 Oct 2002
 */
public class KeyboardInput
{
  /**
   *  The buffered stream that connects to the keyboard so that we can read 
   *  from it sensibly.
   */
  private final BufferedReader in =
    new BufferedReader(new InputStreamReader(System.in));
  /**
   *  Read an <CODE>int</CODE> value from keyboard input.
   *
   * @return    The integer value read in, or zero if the input was invalid.
   */
  public final synchronized int readInteger()
  {
    String input = "";
    int value = 0;
    try
    {
      input = in.readLine();
    }
    catch (IOException e)
    {}
    if (input != null)
    {
      try
      {
        value = Integer.parseInt(input);
      }
      catch (NumberFormatException e)
      {}
    }
    return value;
  }
  /**
   *  Read a <CODE>long</CODE> value from keyboard input.
   *
   * @return    The long value read in, or 0L if the input was invalid.
   */
  public final synchronized long readLong()
  {
    String input = "";
    long value = 0L;
    try
    {
      input = in.readLine();
    }
    catch (IOException e)
    {}
    if (input != null)
    {
      try
      {
        value = Long.parseLong(input);
      }
      catch (NumberFormatException e)
      {}
    }
    return value;
  }
  /**
   *  Read a <CODE>double</CODE> value from keyboard input.
   *
   * @return    The double value read in, or 0.0 if the input was invalid.
   */
  public final synchronized double readDouble()
  {
    String input = "";
    double value = 0.0D;
    try
    {
      input = in.readLine();
    }
    catch (IOException e)
    {}
    if (input != null)
    {
      try
      {
        value = Double.parseDouble(input);
      }
      catch (NumberFormatException e)
      {}
    }
    return value;
  }
  /**
   *  Read a <CODE>float</CODE> value from keyboard input.
   *
   * @return    The float value read in, or 0.0F if the input was invalid.
   */
  public final synchronized float readFloat()
  {
    String input = "";
    float value = 0.0F;
    try
    {
      input = in.readLine();
    }
    catch (IOException e)
    {}
    if (input != null)
    {
      try
      {
        value = Float.parseFloat(input);
      }
      catch (NumberFormatException e)
      {}
    }
    return value;
  }
  /**
   *  Read a <CODE>char</CODE> value from keyboard input.
   *
   * @return    The char value read in, or ' ' (space) if the input was invalid.
   */
  public final synchronized char readCharacter()
  {
    char c = ' ';
    try
    {
      c = (char) in.read();
    }
    catch (IOException e)
    {}
    return c;
  }
  /**
   *  Read an <CODE>String</CODE> value from keyboard input.
   *
   * @return    The String value read in.
   */
  public final synchronized String readString()
  {
    String s = "";
    try
    {
      s = in.readLine();
    }
    catch (IOException e)
    {}
    if (s == null)
    {
      s = "";
    }
    return s;
  }
}
Last updated: August 30, 2006

Computer Science Department - University College London - Gower Street - London - WC1E 6BT - Telephone: +44 (0)20 7679 7214 - Copyright 1999-2006 UCL


 Search by Google