One machine can do the work of fifty ordinary men. No machine can do the work of one extraordinary man

Tuesday, January 1, 2019

How to take input from user in Java

This is one of the common and frequently asked question in Java language. There are few ways to get the user inputs from user via a keyboard.
  • Scanner
  • BufferedReader and InputStreamReader
  • Console
  • DataInputStream (This is deprecated)

Scanner

This is the easiest way to get keyboard inputs from the user. Java Scanner class comes under the java.util package. Normally scanner tokenize the input from the white spaces as a default delimiter. An another advantage of the Scanner is you don't have to write another like to convert the value into a different (required) data format.

import java.util.Scanner;

// Set the default input stream (keyboard) to the scanner object.
Scanner scan = new Scanner(System.in);

// Default next method returns you the value as a String.
String s = scan.next();

// Use the nextInt(), nextDouble() like methods to read the input and parse that directly to a required data format.

int i = scan.nextInt();

// Can read the whole line at once.
String s = scan.nextLine();

Buffered Reader and Input Stream Reader

These two classes comes under the java.io package.

import java.io.BufferedReader; 
import java.io.InputStreamReader; 

BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); 

String s = br.readLine(); 

int i = Integer.parseInt(br.readLine());

Console

The Console class is also comes under the java.io package.

import java.io.Console;
Console console = System.console();

String s = console.readLine();