Skip to main content
Lesson 4 - Simple I/O
Lesson MenuPreviousNext
  
String Input page 7 of 10

  1. The ConsoleIO class has two methods for reading textual input from the keyboard.

  2. The readToken message returns a reference to a String object that has from zero to many characters typed by the user at the keyboard. A token is a sequence of printable characters separated from the next word by white space. White space is defined as blank spaces, tabs, or newline characters in the input stream. White space separates ints and doubles on input. White space also separates words on input. When input from the keyboard, readToken stops adding text to the String object when the first white space is encountered on the input stream from the user.

  3. A readLine message returns a reference to a String object that contains from zero to many characters entered by the user. With readLine, the String object may contain blank spaces and tabs. The newline marker is not included. It is discarded from the input stream.

  4. Input from these String messages is illustrated below.

    import chn.util.*;
    
    public class DemoStringInput
    {
      public static void main(String[] args)
      {
        ConsoleIO keyboard = new ConsoleIO( );
        String word1, word2, anotherLine;
    
        // ask for input from the keyboard
        System.out.print("Enter a line: ");
    
        // grab the first "word"
        word1 = keyboard.readToken();
    
        // grab the second "word"
        word2 = keyboard.readToken();
    
        // ask for input from the keyboard
        System.out.print("Enter another line: ");
        
        // discard any remaining input from previous line
        // and read the next line of input
        anotherLine = keyboard.readLine();
    
        // output the strings
        System.out.println("word1 = " + word1);
        System.out.println("word2 = " + word2);
        System.out.println("anotherLine = " + anotherLine);
      }
    }
    
    Run output:
    
    Enter a line: Hello World! This will be discarded.
    Enter another line: This line includes whitespace.
    word1 = Hello
    word2 = World!
    anotherLine = This line includes whitespace.
    

Lesson MenuPreviousNext
Contact
 ©ICT 2003, All Rights Reserved.