To work with BufferedReader class it
provides a method readLine() to read input. It creates a buffering
character-input stream that uses default-sized input buffer. Again in order to
create an object of BufferedReader we have to create an object of InputStreamReader
first. And in the argument of InputStreamReader we have to pass System.in.
Note – Whenever we work with
any kind of IO operation it throws some kind of exception, so we should handle
or suppress it.
Example –
import
java.io.BufferedReader;
import
java.io.IOException;
import
java.io.InputStreamReader;
public class
BufferReader {
public static void
main(String[] args) throws IOException {
InputStreamReader
isr
= new InputStreamReader(System.in);
BufferedReader
br = new
BufferedReader(isr);
int i,j;
System.out.println("Enter i");
i=br.read();
System.out.println("Eneter j");
j=br.read();
System.out.println(i+j);
}
}
Output –
Enter I // 1
888
Eneter j
112
Enter I // 2
88
Eneter j
112
Enter I // 3
8
Eneter j
69
In the
first output we enter 888 and simply the program exists without taking an input
from user. As it takes input in form of byte here using read(). And it
calculates the ASCII code of 8+8 = 56+56. In the second output also it is same.
But in the third out even we enter 1 digit and press enter it gives out as 69
without taking input from user. Because it considers CR as the second input
whose value is 13 i.e. the value of 8+CR = 56+13 i.e. 69.
Example –
import
java.io.BufferedReader;
import
java.io.IOException;
import
java.io.InputStreamReader;
public class
BufferReader {
public static void
main(String[] args) throws IOException {
InputStreamReader
isr
= new InputStreamReader(System.in);
BufferedReader
br = new
BufferedReader(isr);
int i,j;
System.out.println("Enter i");
i=Integer.parseInt(br.readLine());
System.out.println("Enter j");
j=Integer.parseInt(br.readLine());
System.out.println(i+j);
}
}
Output –
Enter i
5
Enter j
6
11
Note – After parsing the input
as Integer and reading a line instead of character we fulfill our work.
No comments:
Post a Comment