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 showing an example of how to use the Scanner class, here’s a short description of what it does from the 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 Java 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. 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.

Permalink

This helped me substantially! A well explained and accurate example, thanks!

Permalink

Can you please explain as to why do we use the System.in as an input to InputStreamReader, and the InputStreamReader as an input to BufferedReader.

Permalink

thanks... i really learnt from it

its a nice way to explain .. n seems much simpler !!

Permalink

Why are you not using a Scanner object?

Scanner input = new Scanner( System.in );

Permalink

Hi
This are nice snippets ...
I was able to plug-in your "input reader" snippet in to the "system exec" program and was able to interactively execute any system calls!!!
Like if I want to do a bioinformatics blast search I just have to pass the required parameters and it does the job:EG:

[feseha@voyager Jfiles]$ java JavaRunCommand2
Enter your command: bl2seq -i test1.fna -j test2.fna -p blastn

Ans it works like a charm ...

Cool stuff!
Thank you

Permalink

Very good. You have shown me classic and new way to read input at command prompt from user. I want you explain more about Scanner class methods for primitive read operation.

Permalink

Hello i am a very beginner in Java, if i willing to use this code in netbean, what module should i install? Before this i compile this coding on bluej but noting happen.. sorry asking this question but i am really want to know how to use it.

Permalink

Hi,
I´m beggining with java and started making a simple program which counts the digits of the number entered by the user. This is where it all stops working, I tried using the Scanner, but apparently it can be used with string only.

Can anyone help?

import java.util.Scanner;

class NrDigits3 {
public static void main (String[] args) {

int d=1;
System.out.println ("Write the number of which you want to count the digits");

Scanner scanner = new Scanner(System.in);
int n = scanner.nextLine();

if (n<10)
{ System.out.println(d);}

while (n>= 10)
{n=n/10;
d++;
if (n<10)
{System.out.println(d);}
}
}
}

Permalink

Hi,

I would like to know how to mask a password entered using command line.

I had gone through the code given by SUN microsystems for masking a password. But that thread runs into an infinite loop and it seems it has a bug.

I'm using Java 1.5.

Could you guys help me out...

Thanks.

Permalink

What can be done for passwords. I would like to get input but I do not want it to be shown on the screen while it is being typed. How can I accomplish that?

I would imagine that you've figured this out by now, but just in case:

You've got your int set up right now to take a string by using the .nextLine() function of the Scanner class. What you want is the .nextInt(); function. That should clear up the issue for you.

Permalink

We have such command line (Monica 29 Dan 35 Michale 16)
I must to count the average of this numbers and to show these names with their ages.

Can you help me? Should I make an array firstly?

Permalink

Hi,

Thanks for your post dude, its really useful for replacing DataInputStream readLine() method which is deprecated.

Add new comment

The content of this field is kept private and will not be shown publicly.

Anonymous format

  • Allowed HTML tags: <em> <strong> <cite> <code> <ul type> <ol start type> <li> <pre>
  • Lines and paragraphs break automatically.
By submitting this form, you accept the Mollom privacy policy.