INFORMATION & COMPUTER SCIENCE DEPARTMENT, KFUPM

ICS102, SECTIONS 65  (002 Semester)

INTRODUCTION TO COMPUTING

LAB  #03 Console Input and Exception

 

Instructor: Bashir M. Ghandi

 


Objectives:

To gain experience with:

 

1.  Reading Input

Similar to System.out object we have been using for writing output, Java provides System.in for reading input. 

Unfortunately, System.in can only read bytes, while what we normally want to read are characters, strings and numbers.

To solve this problem, Java provides two other classes in the java.io package, which can be used to wrap System.in so that it becomes more useful.

 

InputSreamReader:  This is used to create an object which has a read() method for reading characters.  When creating the object, we pass the System.in object as a parameter.  For example:

InputStreamReader reader = new InputStreamReader(System.in);

 

We can now use the read() method of the reader object to read one character at a time.  For example:

System.out.println(“Enter a character: “);  //a prompt

char ch = (char) reader.read();

System.out.println(“The character you entered is: “+ch);

 

Notice that the read() method does not actually returns a character.  It returns the number corresponding to the character (e.g. 65 for ‘A’), thus, we need to use casting to convert the number to character.

 

BufferedReader: This is used to create an object which has a readLine() method for reading strings.  When creating the object, we pass an InputStreamReader object as a parameter.  For example:

      InputStreamReader reader = new InputStreamReader(System.in);

      BufferedReader stdin = new BufferedReader(reader);

 

In fact we can combine the two statements into one as follows:

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

 

We can now read a string input as follows:

System.out.println(“Enter a your name: “);  //a prompt

String name = stdin.readLine();

System.out.println(“Hello Mr. “+name+ “ What can I do for you?“);

 

Reading numeric values:

To read a numeric value, we use the BufferedReader object to get the value as a string, then we use the parse method of the appropriate wrapper class to convert the string to the corresponding numeric value.

 

Primitive type

Wrapper Class

String to number conversion method

byte

Byte

parseByte()

short

Short

parseSort()

int

Integer

parseInt()

long

Long

parseLong()

float

Float

parseFloat()

double

Double

parseDouble()

 

Example: 

System.out.println(“Enter your age: “);  //a prompt

String input = stdin.readLine();

int age = Integer.parseInt(input);

System.out.println(“After one year you will be: “+age+1);

 

In fact we can combine lines 2 and 3 in the above example into one as follows:

System.out.println(“Enter your age: “);  //a prompt

int age = Integer.parseInt(stdin.readLine());

System.out.println(“After one year you will be: “+age+1);

 

2.  Exceptions.

Exceptions are errors which my be generated by the Java system when something goes wrong with a program.

They can be divided into two:  Checked exceptions and Unchecked Exceptions.

 

Checked Exceptions:  These are exceptions which the compiler checks to ensure that the program has specification for what should be done in case such exceptions occurs.  IOException class and its subclasses formed this group.

 

You can specify how checked exceptions should be handled in two ways; either by throwing the exception forward to a ‘parent’ method using the throws keyword or by using try – catch statement.

 

now, the read() and readLine() methods are designed to generates IOException or one of its sub-classes if something goes wrong, thus, any program that uses these methods must specify how such errors should be handled.

 

The following is complete program that demonstrate reading input and handling exception using the throws keyword.

import java.io.InputStreamReader;

import java.io.BufferedReader;

import java.io.IOException;

public class ReadingInput {

  public static void main(String[] args)throws IOException {

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

   

    System.out.print("Please enter your name: ");

    String name = stdin.readLine();

    System.out.print("Now enter your age: ");

    int age = Integer.parseInt(stdin.readLine());

    System.out.println("Mr. "+name+", after one year you will be "+ (age+1));

  }

}

 

The alternative approach is to use try-catch statement as follows:

import java.io.InputStreamReader;

import java.io.BufferedReader;

import java.io.IOException;

public class CatchingException {

  public static void main(String[] args) {

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

   

    try {

          System.out.print("Please enter your name: ");

          String name = stdin.readLine();

          System.out.print("Now enter your age: ");

          int age = Integer.parseInt(stdin.readLine());

          System.out.println("Mr. "+name+", after one year you will be "+ (age+1));

    }

    catch (IOException e) {

          System.out.println("Sorry, input error: "+e);

    }

  }

}

Unchecked Exception:  These are exceptions, which the compiler does not force the programmer to specify how they should be handled.  The RuntimeException class and its sub-classes formed this group.

Even though the compiler does not check for these errors, it is still good to anticipate such errors and handle them appropriately. 

In the above example, if the user enters something other than integer for age, the parseInt() method will generate a NumberFormatException.  Since this in not a checked exception, the complier will allow the program to compile anyway.  However, we can improve the program by handling the error as follows:

import java.io.InputStreamReader;

import java.io.BufferedReader;

import java.io.IOException;

 

public class UncheckedException {

  public static void main(String[] args) {

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

   

    try {

          System.out.print("Please enter your name: ");

          String name = stdin.readLine();

         

          System.out.print("Now enter your age: ");

          int age = Integer.parseInt(stdin.readLine());

         

          System.out.println("Mr. "+name+", after one year you will be "+ (age+1));

    }

    catch (IOException e) {

          System.out.println("Sorry, input error: "+e);

    }

    catch (NumberFormatException e) {

          System.out.println("Sorry, you must type an integer for the age");

    }

  }

}

 

3.  Assignments

1.        (a)  Open the file ReadingInput.java  and test-run it.  Now remove the throws IOException from the heading of the main method and attempt to compile.  What happened and why?  Correct the program by rewriting throws IOException.

(b)     Open the file CatchingException.java and test-run it.  What happens if you enter an invalid integer such as 27.5?

(c)     Open the file UncheckedException.java and test-run it.  What happens if you enter an invalid integer such as 27.5?

 

2.        Write a Java program that prompts for and reads the length, width, and height (in centimeters) of a closed box. The program should then compute and display

(a)     the volume of the box.

(b)     the surface area of the box.

Note: Use throws keyword to handle IOException.

3.        Write a program that prompts for and read e-mail address a user.  The program them prints the user name and the domain name on different lines.

Note: You must use try-catch to handle IOException.