Tuesday, November 17, 2009

Java's Keyboard Input

Reading from a console input is quite different from C and Java. If in C, we simply use scanf() and in C++ other input operators, in Java, this can be something else.

To read character-based stream inputs, we use tied with BufferedReader. Reader is an abstract class. One of its concrete subclasses is InputStreamReader, which converts bytes to characters. To obtain an InputStreamReader object that is linked to, use the following constructor:

InputStreamReader(InputStream inputStream)

Because refers to an object of type InputStream, it can be used for
inputStream. Putting it all together, the following line of code creates a BufferedReader that is connected to the keyboard:

BufferedReader br = new BufferedReader(new InputStreamReader(;

To implement this, check the sample program to convert weight in pounds to kilograms.

[+/-] show/hide

public class Weight {

public static void main(String args[]) throws IOException{
BufferedReader br= new BufferedReader(new InputStreamReader(;
double weightpds=0.0;
double weightkls=0.0;
String str;

System.out.println("Please enter your weight in pounds:");

weightpds=Double.parseDouble(str); //convert string to double

System.out.println("Your weight of "+weightpds+" pounds is "+weightkls+" kilos.");