Skip to main content
Lesson 4 - Simple I/O
Lesson MenuPreviousNext
  
Reading Input with the ConsoleIO Class page 3 of 10

  1. Some of the programs from the preceding lessons have not been written in the most efficient manner. To change any of the data values in the programs, it would be necessary to change the variable initializations, recompile the program, and run it again. It would be more practical if the program could ask for new values for each type of data and then compute the desired output.

  2. However, accepting user input in Java has some technical complexities. Throughout this curriculum guide, we will use a special class, called ConsoleIO, to make processing input easier and less tedious.

  3. Just as the System class provides System.out for output, there is an object for input, System.in. Unfortunately, Java's System.in object does not directly support convenient methods for reading numbers and strings.

  4. To use the ConsoleIO class in a program, you first need to import from the chn.util package with the statement

    import chn.util.*;
  5. To use a ConsoleIO method, you need to construct a ConsoleIO object.

    ConsoleIO console = new ConsoleIO();

    Next, call one of ConsoleIO methods

    int n  = console.readInt();
    double d  = console.readDouble();
    boolean done  = console.readBoolean();
    String token = console.readToken();
    String line = console.readLine();
  6. Here are some example statements:

    int num1;
    double bigNum;
    String line;
    
    num1 = console.readInt( );
    bigNum = console.readDouble( );
    line = console.readLine( );

    When the statement num1 = console.readInt() is encountered, execution of the program is suspended until an appropriate value is entered on the keyboard.

  7. Any whitespace (spaces, tabs, newline) will separate input values. When reading values, white space keystrokes are ignored. If it is desirable to input both whitespace and non-whitespace characters, the method readLine() is required.

  8. The readToken() method reads and returns the next token from the current line. A token is a String of characters separated by the specified delimiters (whitespace). For example when the following code fragment is executed

    String input = console.readToken();
    System.out.print(input);

    when given an input line of

    twenty-three is my favorite prime number

    would output

    twenty-three

    since this is the first string of characters read before a whitespace value (space) is encountered.

  9. When requesting data from the user via the keyboard, it is good programming practice to provide a prompt. An unintroduced input statement leaves the user hanging without a clue of what the program wants. For example:

    System.out.print("Enter an integer --> ");
    number = console.readInt();

Lesson MenuPreviousNext
Contact
 ©ICT 2003, All Rights Reserved.