All for Joomla All for Webmasters

Reading data from keyboard

There are many ways to read data from the keyboard. For example:

  • InputStreamReader
  • Console
  • Scanner
  • DataInputStream etc.

InputStreamReader class

InputStreamReader class can be used to read data from keyboard.It performs two tasks:

  • connects to input stream of keyboard
  • converts the byte-oriented stream into character-oriented stream

BufferedReader class

BufferedReader class can be used to read data line by line by readLine() method.

Example of reading data from keyboard by InputStreamReader and BufferdReader class

In this example, we are connecting the BufferedReader stream with the InputStreamReader stream for reading the line by line data from the keyboard.

  1. import java.io.*;
  2. class G5{
  3. public static void main(String args[])throws Exception{
  4. InputStreamReader r=new InputStreamReader(System.in);
  5. BufferedReader br=new BufferedReader(r);
  6. System.out.println(“Enter your name”);
  7. String name=br.readLine();
  8. System.out.println(“Welcome “+name);
  9.  }
  10. }
Output:Enter your name
       Amit
       Welcome Amit

Another Example of reading data from keyboard by InputStreamReader and BufferdReader class until the user writes stop

In this example, we are reading and printing the data until the user prints stop.

  1. import java.io.*;
  2. class G5{
  3. public static void main(String args[])throws Exception{
  4.  InputStreamReader r=new InputStreamReader(System.in);
  5.  BufferedReader br=new BufferedReader(r);
  6.  String name=“”;
  7.   while(!name.equals(“stop”)){
  8.    System.out.println(“Enter data: “);
  9.    name=br.readLine();
  10.    System.out.println(“data is: “+name);
  11.   }
  12.  br.close();
  13.  r.close();
  14.  }
  15. }
Output:Enter data: Amit
       data is: Amit
       Enter data: 10
       data is: 10
       Enter data: stop
       data is: stop

PinIt
submit to reddit

Leave a Reply

Top