Java: Console Input-Output (pre Java 5)

You can also read from the console, altho this requires a bit of extra code to get everything working.

  1 
  2 
  3 
  4 
  5 
  6 
  7 
  8 
  9 
 10 
 11 
 12 
 13 
 14 
 15 
 16 
 17 
 18 
 19 
 20 
 21 
// introductory/ConsoleInputOutput.java
// Michael Maus, 28 August 2004
// Write to and read from the console.

import java.io.*;

public class ConsoleInputOutput {
    
    public static void main(String[] args) throws IOException {
        String name;                // Declare a variable to hold the name.
        
        BufferedReader bufReader;   // Declare a BufferedReader variable.
        bufReader = new BufferedReader(new InputStreamReader(System.in));
        
        System.out.println("What's your name, Earthling?");
        name = bufReader.readLine();   // Read one line from the console.
        System.out.println("Take me to your leader, " + name);
        
        System.exit(0);  // Not necessary, but commonly used.
    }
}
Line 5 import java.io.*
You need to specify that you're using classes from teh java.io library.
Line 9 - Pass errors to caller.
To make this program simpler, we're not going to handle any errors that might occur when reading input. If we don't handle this type of error (IOException), we have to say that we might give it (throw it) to the method that called up.
Lines 12-13
Declare and initilize a BufferedReader.
Line 17
Use the reader's readLine() method to get the next input line.