Various methods available for accepting User-Input in java.

There are 4 major ways of doing this .

1.Scanner Class : This is one of the most used techniques , it's easy for passing tokenised input using methods such as nextInt(),etc. One disadvantage is ,it's reading methods are not synchronized .

import java.util.Scanner; //importing the classScanner scan = new Scanner(System.in);// creating a new object of the class
String s = scan.next();
int i = scan.nextInt();//used to read data
  

2.Buffered Reader and InputStreamReader Class: This method we wrap the System.in in an InputStreamReader ,which is wrapped in a BufferedReader. It’s keeps an Index of data/information but it’s difficult to Wrap code .

import java.io.BufferedReader;//importing the classimport java.io.InputStreamReader;
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));//creating a new object of the class
String s = br.readLine();//reading data
int i = Integer.parseInt(s);//converting string to int datatype

3.Console Class:This method utilizes taking input from the command line , it’s usually used in client testing of programs. Main advantage is reading secret word without reverberating the entered characters ,reading is synchronized .It does not work properly in some IDE.

import java.io.Console;//importing class
Console console = System.console();//new object 
String s = console.readLine();//reading data
int i = Integer.parseInt(console.readLine());//converting it to int

4.DataInputStream class : This method uses a primitive read Java data types from an input stream ,machine independent way. Not recommended to use

import java.io.DataInputStream;//importing 
DataInputStream dis = new DataInputStream(System.in);//new object of the class
int i = dis.readInt();//reading the data 

Advertisement

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s