Personal tools
You are here: Home Information Systems Java Platform Introduction 13. Soliciting input

13. Soliciting input

Document Actions
  • Send this
  • Print this
  • Content View
  • Bookmarks

Soliciting input

<-- Previous

Table of Contents

Next -->

The classes we have implemented so far have been fine, but a little frustrating because we have only been able to use literal values to show them in action, i.e. there has been no way to supply the classes with any value we choose during runtime. Java of course has objects that allow us to supply our applications with runtime values, and we'll take a look at some of these.

Using Java packages and their members

Java is huge, and contains a bewildering quantity of packages and classes. Not every Java program needs all the functionality of Java. For example, many Java applications do not need to use graphics or the classes that interface with databases. To keep applications compact and streamlined, Java does not automatically allow your code access to all possible classes. Instead, Java bundles groups of related classes into packages that you can call on when you need to do so. In the same way that a class defines a group of related variables and methods, a package defines a group of related classes.

To get access to classes other than those available by default from the java.lang package, you need to import the specific members of a package that your code will need, or if you will need several of the members of a package you can simply import the entire package. This is very easy to do with the import statement. For example:

import java.io.InputStreamReader;

will import the InputStreamReader class from the java.io package (a group of classes that deal with input and output from Java applications).

IMPORTANT: All import statements must appear in your code before any comments or other code!

Reading console input

To enable our code to get runtime input from users, we need to use the java.io package, which contains classes that build objects that allow us to work with the input and output data streams. Console input is rather cumbersome to program, unfortunately. Console input must read from the System.in object. We have already used the System.out object, which is ready-made to handle printing numbers and strings. System.in however can only read bytes, and the keyboard generates characters not bytes. We have to convert System.in into an object that can read characters, and we do this by instantiating an InputStreamReader object:

InputStreamReader reader = new InputStreamReader(System.in);

InputStreamReaders can read characters, but they can't read a whole string at a time. So, we have to use a further conversion to get to something that can read a whole string or line of input from the console - a BufferedReader object must be instantiated:

InputStreamReader reader = new InputStreamReader(System.in);
BufferedReader console = new BufferedReader(reader);

In fact, the two actions can be combined into one instruction if you like:

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

The BufferedReader object has a readLine() method that allows us to read a whole line of data from our newly minted console object:

String input = console.readLine();

We still have one little problem remaining however - if there is some problem or error when reading console input, the readLine() method throws an exception IOException. An exception (short for 'exceptional event') is the equivalent of what you might think of as an 'error'; in Java exceptions are classes like anything else. We will discuss Java exceptions later on. The Java compiler knows all the checked exceptions that objects can throw, and it demands that you handle the exceptions that your code throws. If you choose not to handle the exceptions, Java requires that you admit that you aren't going to - a sort of truthfulness requirement. To do this you tag your method with a throws specifier:

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

}

To be able to use all these new Java classes in our code we must import them. Let's take a look at an example that uses the Cylinder class we created:

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.IOException;

/**
* Tests using the Cylinder class, and supplying it with 
* constructor arguments from the console.
*/
public class ConsoleCylinder {
   public static void main(String[] args) throws IOException {
      
      BufferedReader console = new BufferedReader(
                 new InputStreamReader(System.in));
      System.out.println("Enter the radius of the Cylinder:");
      double rad = Double.parseDouble(console.readLine());
      System.out.println("Enter the height of the Cylinder:");
      double ht = Double.parseDouble(console.readLine());
      Cylinder myCylinder = new Cylinder(rad, ht);
      System.out.println("\nThe volume of the cylinder is: " + 
        myCylinder.getVolume());
   }
}

Note the following:

  1. The import statements were inserted before any comments or other code.
  2. The console.readLine() method returns a string from the console as typed in by the user. Variables must be provided to capture these returned strings.
  3. Although numbers are not instrinsically objects in Java, we can create number objects by using the java.lang number classes. In the code above, we have parsed the input strings into double precision numbers by using the Double.parseDouble(String str) method of the java.lang.Double class:
    double rad = Double.parseDouble(console.readLine());
    double ht = Double.parseDouble(console.readLine());
    There is more information on casting data types here.
  4. The user input strings once parsed into double precision numbers, are supplied to the Cylinder(aRadius, aHeight) object constructor as its arguments.
  5. Normally, we don't allow the main() method to throw any exceptions, but this is OK here for demonstration purposes and won't cause any problems.  

Compile and test your class.

 

<-- Previous

Table of Contents

Next -->

Copyright 2007-2008, by the Contributing Authors. Cite/attribute Resource. 13. Soliciting input. (2008, July 16). Retrieved June 19, 2013, from UWC Free Courseware Web site: http://free.uwc.ac.za/freecourseware/information-systems/java-platform-introduction/soliciting-input. This work is licensed under a Creative Commons License : Attribution-ShareAlike 3.0. Creative Commons License : Attribution-ShareAlike 3.0