Categories: Snippets

Read Input from User

In Java, there are three different ways for reading input from the user in the command line (console).

1.Using Buffered Reader Class

This method is used by wrapping the System.in (standard input stream) in an InputStreamReader which is wrapped in a BufferedReader, we can read input from the user in the command line.

DataInputStream in = new DataInputStream(System.in);
number = Integer.parseInt(in.readLine());

or

//Enter data using BufferReader 
BufferedReader reader =  
    new BufferedReader(new InputStreamReader(System.in)); 
         
// Reading data using readLine 
String name = reader.readLine();

2. Using Scanner Class

This is probably the most preferred method to take input. The main purpose of the Scanner class is to parse primitive types and strings using regular expressions, however it is also can be used to read input from the user in the command line.

Scanner scan= new Scanner(System.in);

String s = in.nextLine(); 
System.out.println("You entered string "+s); 
  
int i = in.nextInt(); 
System.out.println("You entered integer "+i); 
  
float f = in.nextFloat(); 
System.out.println("You entered float "+f);

3. Using Console Class

It has been becoming a preferred way for reading user’s input from the command line. In addition, it can be used for reading password-like input without echoing the characters entered by the user; the format string syntax can also be used (like System.out.printf()).

// Using Console to input data from user 
String name = System.console().readLine(); 
          
System.out.println(name);

 

Recent Posts

Get jsp response as a string inside servlet

To get jsp response as a string inside servlet is possible by wrapping the HttpServletResponse…

6 years ago

Find Upper Case & Lower Case

Given a string, bellow it shows the boolean condition to find Lowercase characters, Uppercase characters.…

6 years ago

Sorting HashMap by values in ascending and descending order

The below example shows Java program to sort a Map by values in ascending and…

6 years ago