My Keyboard Class

 

Overview

Strange as it may seem, reading data from the keyboard (or console) is not easy in Java. For simplicity, I have written a class named Keyboard that can be used to read data of any primitive data type as well as String objects from the keyboard. The class has automatic, built-in exception handling so an invalid user entry will not crash your program.

 

Source code for the class

Source code for the class is part of the Test project described in the documentation on running Java programs.

 

Using the class

  1. Declare input variables. For example, if your program needs to read some int and double data from the user, you may declare variables such as:

int quantity;
double price;

  1. Prompt the user to enter the data and call the appropriate Keyboard class method to read it. The value returned by the method can be assigned to a variable of the appropriate type. For example, to prompt for and read values for the previously defined quantity and price variables you might code:

System.out.print("Quantity: ");
quantity = Keyboard.readInt();
System.out.print("Price: ");
price = Keyboard.readDouble();

The methods of my Keyboard class are:

readBoolean()
readByte()
readChar()
readDouble()
readFloat()
readInt()
readLong()
readShort()
readString()

Each method returns data of the indicated type and requires no parameters.