Reading Console Input

26 11 2008

The term console refers to a command line interface.All java program automatically import java.lang package.This package defines a class called System,which encapsulates every aspects of runtime environment.System class contains three pre defined stream variables. These fields are declared as ‘public static’ in the System

  • System.in
    refers standard InputStream
  • System.out
    refers standard OutputStream
  • System.err
    refers standard Error Stream

There is no obvious System.in.readLine() in the InputStream API. The closest thing available is the readLine method in the BufferedReader class. The System class in the java.lang package automatically creates an InputStream object that is connected to the keyboard. It is called System.in and is part of the java.lang package.We will use the System.in object to create an instance of the InputStreamReader class and then use that object to create an instance of the BufferedReader class.

Steps for console based user input:

  • Use the System.in object to create an InputStreamReader object.

  • Use the InputStreamReader object to create a BufferedReader object.

  • Display a prompt to the user for the desired data.

  • Use the BufferedReader object to read a line of text from the user.

Example

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

public class TestConsoleInput {

	public static void main(String[] args) throws IOException {
		int count =0;
		BufferedReader console = new BufferedReader( new InputStreamReader(System.in));

		System.out.println("What is your name?");

		//Reading Character input
		String name = console.readLine();

		//Reading Integer input
		System.out.println("How many eyes do you have?[ Please enter numeric values ] ");
		String no_eyes = console.readLine();
		try{
		count = Integer.parseInt(no_eyes); // convert string to integer
		}catch (Exception e) {
			System.out.println("[ "+no_eyes+ " ] is not numeric");
		}

		System.out.println("Name : "+name);
		if(count != 0){
			System.out.println("Number of eyes : "+count);
		}
	}
}

Output:
	What is your name?
	Joe
	How many eyes do you have?[ Please enter numeric values ]
	2
	Name : Joe
	Number of eyes : 2
Advertisement

Actions

Information

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Connecting to %s




Follow

Get every new post delivered to your Inbox.