How to read interactive command-line input with Java

Java command-line FAQ: How do I read command line input from a Java application (interactively)?

Solution: As of Java 5 (and newer Java versions), the best way to solve this problem is to use the Java Scanner class. Before I show how to use the Scanner class, here’s a short description of what it does from its Javadoc:

“A simple text scanner which can parse primitive types and strings using regular expressions. A Scanner breaks its input into tokens using a delimiter pattern, which by default matches whitespace. The resulting tokens may then be converted into values of different types using the various next methods.”

A Java Scanner class example

The following source code shows how to create and use a Java Scanner instance to read command-line input:

import java.util.Scanner;

/**
 * A Java Scanner class example from http://alvinalexander.com
 */
public class JavaScannerExample
{

  public static void main (String[] args)
  {
    // create a scanner so we can read the command-line input
    Scanner scanner = new Scanner(System.in);

    //  prompt for the user's name
    System.out.print("Enter your name: ");

    // get their input as a String
    String username = scanner.next();

    // prompt for their age
    System.out.print("Enter your age: ");

    // get the age as an int
    int age = scanner.nextInt();

    System.out.println(String.format("%s, your age is %d", username, age));

  }

}

When you run this program the command-line interaction looks like this:

Enter your name: Al
Enter your age: 42
Al, your age is 42

Note that the next* methods of the Scanner class can throw exceptions that you'll need to handle. This is demonstrated in the following example, where I intentionally don’t enter an int value for the age:

Enter your name: Al
Enter your age: Fred
[error] (run-main-0) java.util.InputMismatchException
java.util.InputMismatchException
	at java.util.Scanner.throwFor(Scanner.java:909)
	at java.util.Scanner.next(Scanner.java:1530)
	at java.util.Scanner.nextInt(Scanner.java:2160)
	at java.util.Scanner.nextInt(Scanner.java:2119)
	at ScannerTest.main(ScannerTest.java:21)
	at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
	at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
	at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
	at java.lang.reflect.Method.invoke(Method.java:606)

The Scanner class “next” methods

The Scanner class has a collection of next* methods that you can use to read a users’ command-line input. Some of the most common methods are shown here:

next           finds and returns the next complete token from this scanner
next(pattern)  returns the next token if it matches the specified pattern
nextBoolean    returns true if the next token in this scanner's input can be interpreted 
               as a boolean value using a case insensitive pattern created from the string "true|false"
nextByte       scans the next token of the input as a byte
nextDouble     scans the next token of the input as a double
nextFloat      scans the next token of the input as a float
nextInt        scans the next token of the input as an int
nextLine       advances this scanner past the current line and returns the input that was skipped
nextLong       scans the next token of the input as a long
nextShort      scans the next token of the input as a short

It’s fairly obvious how most of those methods work if you’re prompting a user for one input value at a time, but things can get interesting when you use pattern-matching to parse user input.

The Javadoc shows a little bit about how to use pattern-matching with a Scanner, but IMHO it’s not a good idea to use regex patterns when trying to read interactive command-line input. There are a lot of things that can go wrong when you’re reading user input, and when you try to match interactive command-line input against a regex, well, let’s just say that you’ll need to handle a lot of exceptions. Whenever I do this I just tend to read the user’s input as a String, and then I try to parse that String once I have it.

As a final note, I want to reiterate that all of these methods can throw exceptions, as I demonstrated in the example above.

Reading Java command-line input in the good old days

As a quick note, while this is now basically legacy information, if you want to see how we read command line input in Java in the days before Java 5, see my article titled, Java code to read command-line input.