How to read from console in Java?

UPDATED: 27 December 2016
Following excerpt shows how you can read String, Number, etc... from console in Java using java.util.Scanner.

Source code (ScannerExample.java)
import java.util.Scanner;

/**
 * Example of scanner in Java.
 * @author javaQuery
 * @date 27th December, 2016
 * @Github: https://github.com/javaquery/Examples
 */
public class ScannerExample {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        
        System.out.println("Username:");
        String username = scanner.nextLine();
        System.out.println("Password:");
        String password = scanner.nextLine();
        System.out.println("Enter random number(Read interger from console):");
        int number = scanner.nextInt();
        
        System.out.println("[Username:" + username + ", Password: " + password + ", Number: " + number + "]");
    }
}

Output
Username:
vicky.thakor
Password:
pass1word
Enter random number(Read interger from console):
123456
[Username:vicky.thakor, Password: pass1word, Number: 123456]

0 comments :