Pages

Accepting Input from Keyboard


A stream represents flow of data from one place to other place. Streams are of two types in java. Input streams which are used to accept or receive data. Output streams are used to display or write data. Streams are represented as classes in java.io package. 
· System.in: This represents InputStream object, which by default represents standard input device that is keyboard.
· System.out: This represents PrintStream object, which by default represents standard output device that is monitor.
· System.err: This field also represents PrintStream object, which by default represents monitor. System.out is used to display normal messages and results whereas System.err is used to display error messages.

To accept data from the keyboard:
· Connect the keyboard to an input stream object. Here, we can use InputStreamReader that can read data from the keyboard.
InputSteamReader obj = new InputStreamReader (System.in);
· Connect InputStreamReader to BufferReader, which is another input type of stream. We are using BufferedReader as it has got methods to read data properly, coming from the stream. BufferedReader br = new BufferedReader (obj);
The above two steps can be combined and rewritten in a single statement as:
BufferedReader br = new BufferedReader (new InputStreamReader (System.in));
· Now, we can read the data coming from the keyboard using read () and readLine () methods available in BufferedReader class.
Figure: Reading data from keyboard

Accepting a Single Character from the Keyboard:
· Create a BufferedReader class object (br).
· Then read a single character from the keyboard using read() method as: char ch = (char) br.read();
 · The read method reads a single character from the keyboard but it returns its ASCII number, which is an integer. Since, this integer number cannot be stored into character type variable ch, we should convert it into char type by writing (char) before the method. int data type is converted into char data type, converting one data type into another data type is called type casting.
Accepting a String from Keyboard:
· Create a BufferedReader class object (br).
· Then read a string from the keyboard using readLine() method as: String str = br.readLine ();
· readLine () method accepts a string from keyboard and returns the string into str. In this case, casting is not needed since readLine () is taking a string and returning the same data type.

Accepting an Integer value from Keyboard:
· First, we should accept the integer number from the keyboard as a string, using readLine () as:  String str = br.readLine ();
· Now, the number is in str, i.e. in form of a string. This should be converted into an int by using parseInt () method, method of Integer class as: int n = Integer.parseInt (str);
     If needed, the above two statements can be combined and written as:
                        int n = Integer.parseInt (br.readLine() );
· parseInt () is a static method in Integer class, so it can be called using class name as Integer.parseInt ().
· We are not using casting to convert String type into int type. The reason is String is a class and int is a fundamental data type. Converting a class type into a fundamental data type is not possible by using casting. It is possible by using the method Integer.parseInt().

Accepting a Float value from Keyboard:
· We can accept a float value from the keyboard with the help of the following statement: float n = Float.parseFloat (br.readLine() );
· We are accepting a float value in the form of a string using br.readLine () and then passing the string to Float.parseFloat () to convert it into float. parseFloat () is a static method in Float class.

Accepting a Double value from Keyboard:
· We can accept a double value from the keyboard with the help of the following statement: double n = Double.parseDouble (br.readLine() );
· We are accepting a double value in the form of a string using br.readLine () and then passing the string to Double.parseDouble () to convert it into double. parseDouble () is a static method in Double class.

Accepting Other Types of Values:
· To accept a byte value:                      byte n = Byte.parseByte (br.readLine () );
· To accept a short value:         short n = Short.parseShort (br.readLine () );
 · To accept a long value:                      long n = Long.parseLong (br.readLine () ); · To accept a boolean value:             boolean x = Boolean.parseBoolean (br.readLine () );
If read () / readLine () method could not accept values due to some reason (like insufficient memory or illegal character), then it gives rise to a runtime error which is called by the name IOException, where IO stands for Input/Output and Exception represents runtime error.But we do not know how to handle this exception, in Java we can use throws command to throw the exception without handling it by writing:
                   throws IOException at the side of the method where read ()/ readLine () is used.

Program 1: Write a program to accept and display student details.
// Accepting and displaying student details.
import java.io.*; class StudentDemo
{           public static void main(String args[]) throws IOException
                        {          // Create BufferedReader object to accept data
    BufferedReader br =new BufferedReader (new InputStreamReader (System.in));
                                    //Accept student details
                                    System.out.print ("Enter roll number: ");                                   int rno = Integer.parseInt (br.readLine());                                  System.out.print (“Enter Gender (M/F): “);                     
         char gender = (char)br.read();
                                    br.skip (2);
                                    System.out.print ("Enter Student name: ");
                                    String name = br.readLine ()
                                    System.out.println ("Roll No.: " + rno);
                                    System.out.println ("Gender: " + gender);
                                    System.out.println ("Name: " + name);
                        }
}
 In the above program after accepting gender of the student, br.skip (2) is used. The reason is that we used read () method to accept the gender value and then readLine () is used to accept the name. When we type M for gender and press enter, then it releases a \n code. So at gender column, we are giving
two characters M and \n. But, read () method takes only the first character and rejects the next character, i.e. \n, which is trapped by the next readLine () method and name will accept \n. For this purpose, we can use skip () method of BufferedReader, which helps in skipping a specified number of characters. Suppose we take \n as two characters; now to skip them, we can write br.skip (2);