Java: How to get input from System.console()

Using Console to read input (usable only outside of an IDE):

System.out.print("Enter something:");
String input = System.console().readLine();

Another way (works everywhere):

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class Test {
    public static void main(String[] args) throws IOException { 
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        System.out.print("Enter String");
        String s = br.readLine();
        System.out.print("Enter Integer:");
        try {
            int i = Integer.parseInt(br.readLine());
        } catch(NumberFormatException nfe) {
            System.err.println("Invalid Format!");
        }
    }
}

System.console() returns null in an IDE.
So if you really need to use System.console(), read this solution from McDowell.

Leave a Comment