Additional Lines Needed | Heaton Research

Additional Lines Needed

Get the entire book!
Java for the Beginning Programmer

In addition to the two lines just discussed, there are quite a few additional lines of program code that are necessary to make this program work. While these lines do not directly interact with the user, they are quite necessary. I will now show you what they are for, so that you can include them in your own programs.

Try and Catch Blocks

If you look at Listing 4.1 you will see that there is a try and catch block. Try/catch blocks are used to handle errors. If any error occurs in the middle of the try block, the program immediately executes the catch block. If no error occurs, the catch block will not be executed.

The general form of a try/catch block is shown here.

try
{
  // program code that may cause an error
}
catch(Exception e)
{
  // program code to be executed if an error occurs
}

If you are going to have a catch block, you must have a try block. It makes no sense for them to exist separately. If an error occurs anywhere within the try block, the program will immediately leave the try block and execute the code in the catch block.

This allows the program to continue executing, even though an error has occurred. Usually, you will insert some code to display an error message to the user when the catch block is executed.

You may be wondering, what error could possibly happen while reading data from the keyboard. In reality, there is no error that can occur. However, because readLine is a part of the Input/Output system of Java, you must register to handle the error, even though it cannot actually happen.

Setting up to Read User Input

In addition to the try/catch block, you must also setup a few objects to allow your program to read from the user. These objects are created by using the following two lines:

InputStreamReader inputStreamReader = 
  new InputStreamReader ( System.in );
BufferedReader in = 
  new BufferedReader ( inputStreamReader );

These lines deal with Java’s Input/Output system and allow you to read data from the user line by line. It is not important that you understand how these two lines work. You simply need to be aware that they must be included in any program that needs to read user input from the console keyboard.

Once you have executed these two lines you will be left with an object named “in”. This object is used to call the readLine method.

Copyright 2005-2008 by Heaton Research, Inc.