Reading data from keyboard

Commonly used methods to read data from keyboard in Java are :

1)Using BufferedReader & InputStreamReader

See the code  shown below.It reads data from keyboard as String.

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

/**
User: Bijoy
Date: 12/10/12
Time: 11:24 AM
*/

public class IORead {
public static void main(String[] args) {
BufferedReader buff = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter the String to be read :");
try {
String value = buff.readLine();
System.out.println("Entered String = " + value);
} catch (IOException e) {
e.printStackTrace();
}
}
}

sample Output

Enter the String to be read :

Coderpanda

Entered String = Coderpanda

If it is needed to read integer or double values from keyboard , use appropriate wrapper class method such as  : Integer.parseInt(value).

2)Using Scanner

Scanner is an inbuilt class in  util package.It has methods like nextLine() to read data from keyboard.See the sample program shown below.

import java.util.Scanner;
/**
User: Bijoy
Date: 12/10/12
Time: 2:50 PM
*/
public class ScannerSample {
public static void main(String[]args){
Scanner sc = new Scanner(System.in);
System.out.println("Enter string ");
String value = sc.nextLine();
System.out.println("value entered = "+value);
}
}

Sample Output

Enter string
coderpanda
value entered = coderpanda

We have other options to read from keyboard , for example using console. If we have an active console we can  use  it. If there is no active console while running the application , null pointer exception will be thrown.

 

Leave a Reply

Your email address will not be published. Required fields are marked *