Sunday, 26 January 2014

How to read input from command line in Java using Scanner

Java 5 introduced a nice utility called java.util.Scanner which is capable to read input form command line in Java. Using Scanner is nice and clean way of retrieving user input from console or command line. Scanner can accept InputStream, Reader or simply path of file from where to read input. In order to reading from command line we can pass System.in into Scanner's constructor as source of input. Scanner offers several benefit over classical BufferedReader approach, here are some of benefits of using java.util.Scanner for reading input from command line in Java:

1) Scanner supports regular expression, which gives you power to read only matching pattern from input.
2) Scanner has methods like nextInt(), nextFloat() which can be used to read numeric input from command line and can be directly used in code without using Integer.parseInt() or any other parsing logic to convert String to Integer or String to double for floating point input.

Reading input from command line should be the first few thing which new Java programmer should be taught as it help them to write interactive program and complete programming exercise like checking for prime number, finding factorial of number, reversing String etc. Once you are comfortable reading input from command line you can write many interactive Java application without learning  in GUI technology like Swing or AWT.

Java program to read input from command prompt in Java

Here is sample code example of How to read input from command line or command prompt  in Java using java.util.Scanner class:

import java.io.IOException;
import java.util.Scanner;

public class ReadInputScannerExample {

    public static void main(String args[]) throws IOException  {
 
        Scanner scanner = new Scanner(new InputStreamReader(System.in));
        System.out.println("Reading input from console using Scanner in Java ");
        System.out.println("Please enter your input: ");
        String input = scanner.nextLine();
        System.out.println("User Input from console: " + input);
        System.out.println("Reading int from console in Java: ");
        int number = scanner.nextInt();
        System.out.println("Integer input: " + number);
     
    }
 
}

Output:
Reading input from console using Scanner in Java
Please enter your input:
number
User Input from console: number
Reading int from console in Java:
1232
Integer input: 1232

Just note that java.util.Scanner nextInt() will throw "Exception in thread "main" java.util.InputMismatchException" exception if you entered String or character data which is not number while reading input using nextInt(). That’s all on how to read user input from command line or command prompt in Java.

Related Java programming tutorials for beginners

No comments:

Post a Comment