Saturday 25 May 2013

User I/O in Java

This example does console input/output in Java. It asks the user to type his / her name then says Hello.

At the start of the program, the java.io package is imported. This contains code to do system input / output. The asterisk which follows means that the program may want to use any of the classes in java.io.

The program creates an InputStreamReader class variable called isr to read what the user types. It also creates a BufferedReader class variable called br to store it temporarily.

The try block reads the user's input and the catch block handles exceptions: 

UBUNTU > cat prog31.java
import java.io.*;
public class prog31
{
public static void main(String[] args)
  {
  System.out.print("What is your name? ");
  InputStreamReader isr = new InputStreamReader(System.in);
  BufferedReader br = new BufferedReader(isr);
  try
    {
    String your_name = br.readLine();
    System.out.println("Hello " + your_name);
    }
  catch (IOException test)
    {
    System.out.println("I/O error");
    }
  }
}
UBUNTU > javac prog31.java
UBUNTU > java prog31
What is your name? Andrew
Hello Andrew
UBUNTU >