How to read from command line in Java

Reading from command line to get User input is a common task. Let’s see how to do it in Java

Java provides java.util.Scanner class to help read from Console. Let’s see the code that shall take name and age as input and print it back.

package com.codezuzu;

import java.util.Scanner;

/**
 * codezuzu.com
 */
public class ConsoleReader {

  public static void main(String[] args) {
    Scanner scanner = new Scanner(System.in);
    System.out.println("Please enter your Name:");
    String name = scanner.nextLine();
    System.out.println("Please enter your age:");
    int age = scanner.nextInt();
    System.out.println(String.format("%s your age is %d", name, age));
  }

}

We initialize Scanner with System.in to set command line as source of input. Scanner can also get input from file.
Scanner provides various API’s to get the data in desired data types. We use nextLine() to get the name and nextInt() to get the age. Once we run, here it how the output looks

Please enter your Name:
codezuzu
Please enter your age:
1
codezuzu your age is 1

What if we add invalid age?

If we enter invalid input, it shall throw an exception providing an ability to handle it.

Please enter your Name:
codezuzu
Please enter your age:
code
Exception in thread "main" java.util.InputMismatchException
	at java.util.Scanner.throwFor(Scanner.java:864)
	at java.util.Scanner.next(Scanner.java:1485)
	at java.util.Scanner.nextInt(Scanner.java:2117)
	at java.util.Scanner.nextInt(Scanner.java:2076)
	at com.codezuzu.ConsoleReader.main(ConsoleReader.java:15)
	at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
	at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
	at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
	at java.lang.reflect.Method.invoke(Method.java:483)
	at com.intellij.rt.execution.application.AppMain.main(AppMain.java:134)

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.