Keyboard Input

A simple keyboard example A method for getting keyboard input
Summary Practice Exercise

Learning Outcomes

On completion of this section you will know:

Download pdf version

Introduction

Up to now we have not read any data from the keyboard. This has lead us use very artificial examples earlier when, for example, we were demonstrating conversion from String data type to primitive double data type. The reason for not introducing keyboard reading up to now is that to do in Java one must be familiar with exception handling, which in turn means we must be familiar with objects and classes. Furthermore we must have at least a basic knowledge of arrays.

Now that we have those topics under our belts we can proceed to look at keyboard input.

A simple Keyboard Example

Go to top

Listing 12.1 below is a ridiculously simple payroll application where we don’t even calculate the tax or the nett.  The main purpose of this application is to demonstrate how data is read from the keyboard and then converted to the primitive numeric types that we use to calculate the payroll.

Before looking at the code let us firstly examine a few concepts involved here. Firstly when the programme reads data that resides outside of its own memory area, the methods used tend to throw exceptions. The reason for this is that since the programme is going to read data, of whose creation it had no control, it has no guarantee that the data will be in a format that it can read or that the source of the data will even be available.  For that reason any methods that read external data are designed to throw exceptions if for any reason they cannot read the same data.

The other thing we have to point out is that data is read from the keyboard in the form of an array of bytes. As we would rarely use byte arrays for normal data processing, this incoming data has to be converted to String. If it needs to be converted to a numeric type then the appropriate parse methods of the classes that encapsulate the primitive numeric data types can be used.

With this extra knowledge let us then examine the code for our first direct user data input.

Listing 12.1

 1

import java.io.IOException;

 2

public class Untitled1

 3

{

 4

  public static void main(String[] args)

 5

  {

 6

    byte[] input = new byte[20];

 7

    double hours, rate, gross;

 8

    String temp;

 9

    try

 10

    {

 11

      System.out.println("Enter hours");

 12

      System.in.read(input);

 13

      temp = new String(input);

 14

      hours = Double.parseDouble(temp);

 15

      System.out.println("Enter rate");

 16

      System.in.read(input);

 17

      temp = new String(input);

 18

      rate = Double.parseDouble(temp);

 19

      gross = hours * rate;

 20

      System.out.println("Hours " + hours);

 21

      System.out.println("Rate " + rate);

 22

      System.out.println("Gross " + gross);     

 23

    }

 24

    catch(IOException e)

 25

    {

 26

      System.out.print(e.toString());

 27

    }

 28

  }

 29

}

 

We stated that data coming from the keyboard is read as an array of bytes and thus at line 6 we declare an array of 20 bytes called input. The rest of the required variables are declared at line 7. At line 8 we have a String variable temp that will temporarily hold the incoming data in text format before it is converted to primitive double.

At line 12 we use the System.in.read in order to read the keyboard data.  The read method throws an exception of the class IOException and thus its calling has to be done inside a try block.  The data read from the keyboard is stored in the array input which has been placed between the brackets of the read method. If the reading has been successful then control passes to line 13 where the byte array is converted to String. At line 14 the parseDouble method is used to convert this to the primitive double type.

Lines 15 – 18 simply repeat the logic of lines 11 – 14.  The rest of the body of the try block is concerned with the processing and output of the data.

A Method for getting Keyboard Input

Go to top

The above code, although it demonstrated how to get data from the keyboard, is quite clumsy – especially in the way that lines 11 – 14 are repeated in lines 15 – 18.  a somewhat more elegant version of the same application is presented below in Listing 12.2.

Listing 12.2

 1

import java.io.IOException;

 2

public class Untitled1

 3

{

 4

  public static void main(String[] args)

 5

  {

 6

    byte[] input = new byte[20];

 7

    double hours, rate, gross;

 8

    String temp;

 9

    try

 10

    {

 11

      temp = readKB("Enter Hours");

 12

      hours = Double.parseDouble(temp.trim());

 13

      temp = readKB("Enter Rate");

 14

      rate = Double.parseDouble(temp);

 15

      gross = hours * rate;

 16

      System.out.println("Hours " + hours);

 17

      System.out.println("Rate " + rate);

 18

      System.out.println("Gross " + gross);     

 19

    }

 20

    catch(NumberFormatException e)

 21

    {

 22

      System.out.print(e.toString());

 23

    }

 24

  }

 25

  public static String readKB(String prompt)

 26

  {

 27

     String value;

 28

     byte[] input = new byte[20];

 29

     System.out.println(prompt);

 30

     try

 31

     {

 32

       System.in.read(input);

 33

       value = new String(input);

 34

     }

 35

     catch(IOException e)

 36

     {

 37

       value = new String("");

 38

     }

 39

     return value;

 40

  }

 41

}

 

The first part of this listing we shall look at is the method readKB, which spans lines 25 – 40. In the body of the method are declared the String variable that will hold the converted value of the incoming data and the byte array that will be used to read the keyboard. In the body of the try block the keyboard data is read into the byte array input at line 32 and that array is converted to a String and stored in the variable value at line 33.

In the event of an exception occurring at line 32 the catch block is entered and at line 37 value is assigned a blank.

The blank or the converted data is returned at line 39.

 Go to top

Summary

 Go to top
The method System.in.read() reads data from the keyboard in the form of an array of bytes. This method can throw ain IOException and therefore must be called in the try part of a try..catch construct. Furthermore the byte array that contains the keyboard data has be be converted to a String object before we can use it.

Practice

 Go to top
Copy the code in listing 12.1 above into a project and run it. Ensure that it runs correctly without producing an error. Once it is running correctly modify it so that the employee’s name, surname and job description are accepted from the user and then displayed along with the results of the payroll calculation
Copy the code in Listing 12.2 and test it in exactly the same way as the code from listing 12.1.

Exercise

 Go to top
Modify Exercise 7.2 so that the constructor that accepts no arguments will instead accept the lawnmower category and the amount sold directly from the user as keyboard input.
The easiest way to do this is to copy the code of the method readKB from listing 12.2 into your class as a private method. The code in the constructor then call the method and process the data it returns in exactly the same way as in lines 11 – 14 of Listing 12.2