Reading Input from User

Section 3: How to Accept Input by using BufferedReader?

The third way to read input from users is by using BufferedReader. This class is present in the “java.io” package. For creating the object of BufferedReader class we need to pass an object of InputStreamReader which is also present in the same package. But to create an object of InputStreamReader we need to pass “System.In”.

So Object of BufferedReader can be created as Below.

In the following program, we are reading the number entered by the user and calculating its square.

readLine() method is used to read the value entered by the user.
Note that the readLine() method throws the exception so we need to handle it by using try-catch or by adding throws exception in our main method. Exception handling we will see later in this course. For now, let’s just ass throws an exception in our method. This Exception is IOException which also comes under the same java.io package.
This is a known exception, it means at compile time compiler knows that the readLine method throws this exception, hence if we did not handle this exception compiler will not allow us to compile the program and will give a compile-time error as shown below (remove throws IOException from above code to generate this error at compile time).

Since the readLine() method returns the value in String format, we need to parse this string into Integer. For this parsing, we have the parseInt(String value) method of wrapper class Integer. Similarly, for float, we have wrapper class as Float having method as parseFloat(String value). We will see wrapper classes later.

-A blog by Shwetali Khambe

Related Posts