USER INPUT IN JAVA
Hello Friends,
Today I am going to tell you two ways to take input from user in java.
As we know that java is an object oriented language so any work is based on classes and objects.
First Way :
In this method we use two java classes named as :
InputStreamReader and BufferedReader
There are 2 type of streams : Input Stream and Output Stream
Input Stream are those stream which receive or read data coming from some other place. and Output Stream are those stream which send and write data
All the streams are represented by the classes in java.io package, so we need to import this package in our program.
import java.io.*;
To take input from the keyboard we use System.in
System.in: it represent InputStream object, which by default represent standard input device i.e. Keyboard
Now first step to create object of InputStreamReader class and connect keyboard to it
1) InputStreamReader obj = new InputStreamReader(System.in);
Second we have to create the object of BufferedReader class and connect the previous object to that
2) BufferedReader br = new BufferedReader(obj);
Now to read data we have 2 methods of BufferedReader Class
read() and readLine();
read() : this method is used to read a single character from the keyboard, but it returns the ASCII value of that character. So to print the character on screen we have to convert integer (ASCII value) to char data type
char ch = (char) br.read();
readLine(): this method read a string from keyboard such as :
String s = br.readLine();
If we want to take integer we have to convert it
int n = Integer.parseInt(br.readLine());
In the same way we can convert string in any of primitive data type.
Example :
import java.io.*;
class First
{
public static void main(String args[]) throws IOException
{
//above two lines in article can be combimed and written as :
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.print("enter your name, gender and age");
String name = br.readLine();
char gender = (char)br.read();
int age = Integer.parseInt(br.readLine());
// display details
System.out.println("name = " + name);
System.out.println("gender = " + gender);
System.out.println("age = " + age);
}
The only thing which is not discussed till now is Throws IOException i have written right after main method. it is because :
read() method of BufferedReader class throw an runtime exception named IOException and our program stuck bcaz of the exception . there are 3 ways to handle exception
1) put the code generating exception in try block and define a catch block below
2) throw the exception using throw keyword
3) throws keyword is used at the method definition, which is generating Exception
so we are using 3rd way in this program ..
I hope it will be helpful for those who is studying java first time ......
If you have any question, u can ask in comment ..
Thank You ...