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, 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.

This was very helpful for me

This was very helpful for me as I am a beginner in Java.Thanks a lot.

I 'm too beginner in java.

I 'm too beginner in java. Thanks a lot for a good tutorial on basics of getting input from command line.

Nice

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

Please explain

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.

Sure. System.in represents

Sure. System.in represents the standard input stream. As the System Javadoc states, "This stream is already open and ready to supply input data. Typically this stream corresponds to keyboard input or another input source specified by the host environment or user." So that's where we start to get the keyboard input.

The InputStreamReader is the "bridge from byte streams to character streams", so it helps perform that conversion, as I want to deal with keystrokes as characters in my code, and not bytes. (A different programmer might want to deal with them as bytes, but because I know I want to use the BufferedReader's readLine() method, I'm going down this road.)

The BufferedReader "Reads text from a character-input stream, buffering characters so as to provide for the efficient reading of characters, arrays, and lines." I use it because the readLine() method makes it really easy to deal with the input as a String. If I didn't wrap it around the InputStreamReader, I'd have to use the InputStreamReader's read() method, which returns one character at a time.

cmd line method is great

thanks... i really learnt from it

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

Why so lengthy?

Why are you not using a Scanner object?

Scanner input = new Scanner( System.in );

Read command line input with Scanner

Thanks for the tip. To answer your question, this article was written before Java 5 and the Scanner class came around.

Here's an updated version of this class, demonstrating how to read command line input from a Java program using the Scanner class:

import java.util.Scanner;

public class ScannerTest
{

  public static void main (String[] args)
  {
    //  prompt the user to enter their name
    System.out.print("Enter your name: ");

    // get their input
    Scanner scanner = new Scanner(System.in);

    // there are several ways to get the input, this is 
    // just one approach
    String username = scanner.nextLine();

    // test the String
    if (username.trim().equals(""))
    {
      System.out.println("Hmm, I didn't get your name");
    }
    else
    {
      System.out.println("Thanks for the name, " + username);
    }
  }

}

As mentioned, there are several ways to get input from the Scanner class, and I recommend taking a look at the Scanner class javadoc.

is there a way to get user

is there a way to get user input without the scanner class?

Yes, just use the ReadString

Yes, just use the ReadString class shown near the top of this article. It was written before the Scanner class was available, so it just uses and InputStreamReader and BufferedReader.

is this prog wrong...?i did in netbeans, it not working.help me

import java.io.*;

public class BRRead
{

public static void main( String args []) throws IOException
{
char c;
BufferReader br=new BufferReader(new InputStreamReader(System.in));
System.out.println("Enter character, 'q' to quit");

do{
c = (chat) br.read();
System.out.println(c);
}while(c!='q');
}
}

Nice'n easy

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

Comment

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.

use in netbean

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.

Corrected BufferedReader example

Here's a corrected version of your code:

import java.io.*;

public class BRRead
{
  public static void main( String args []) throws IOException
  {
    BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
    System.out.println("Enter character, 'q' to quit");

    char c;
    while ( (c = (char)br.read()) != 'q')
    {
      System.out.println("char: " + c + ".");
    }
  }
}

You were very close, except for a few typos.

Also, sorry, I don't use NetBeans, and I don't know how to make this work from there. I just run it from the command line (Unix command line, in my case).

I hope that is helpful, and thanks for the nice "while loop" example of this code.

 

NetBeans

I'm sorry, I don't use NetBeans, and so I can't be much help here, but I thought I'd post your comment here in case someone else can answer it.

How to read numbers?

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);}
}
}
}

How to mask a command line password input in java

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.

How about passwords

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?

Java Scanner with numbers

Sorry for the late reply, but the Scanner class has numeric methods like nextInt, nextFloat, etc., that should work. If for some reason those don't work, read the input as a String, and convert it to a number, as in this Java String to int example.

Java command line password input/masking

Masking passwords on the command line with Java is tricky business. If you know you're on a Unix system, you might be able to print something from your Java program to tell the terminal not to display the input the user types, and then set it back to normal when you're done. I haven't done this in a long time, but you can do it with the Unix stty command, or even with a simple echo statement.

A second approach is to have your Java program run a separate thread that masks the password as the user types it, essentially deleting each character after the user types it. This is shown in this Sun/Oracle password masking tip.

How to Read Numbers

If we Change slightly
.
.
.
.
int n = scanner.readInt();
.
.
.
It will be OK.

sacnner.nextInt();

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.

How to read numbers and words separatly?

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?

Read as String, then convert

Yes, I would just read them in as String objects, then convert the expected numbers to int with Integer.parseInt(). If you know the input should be a String followed by an int (then repeat) this is a good approach.

BufferedReader readLine()

Hi,

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

Post new comment

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