0

I am trying to retrieve a string from my console with System.console().readline(); but when i run the program to get the string it throws a exception.

Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException

How can i get data from my console and put it in a string? This is what i tried:

String response = System.console().readline();
System.out.println(response);
Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
The_Monster
  • 494
  • 2
  • 7
  • 28
  • 7
    Try using a Scanner, http://docs.oracle.com/javase/1.5.0/docs/api/java/util/Scanner.html. You can create a new Scanner(Systsem.in) and then get strings with .next() (and check if input is available with .hasNext()) – Pphoenix Jun 11 '14 at 09:29
  • Do you want to read input ? or any text ? – Ninad Pingale Jun 11 '14 at 09:32
  • Read this: http://stackoverflow.com/questions/8560395/how-to-use-readline-in-java – Vito Gentile Jun 11 '14 at 09:34
  • System.console() returns null in an IDE, so if you really need to use System.console(), read this solution from McDowell.http://illegalargumentexception.blogspot.in/2010/09/java-systemconsole-ides-and-testing.html – Jaimin Patel Mar 01 '16 at 09:54

2 Answers2

2

Use Scanner for this purpose.

Scanner sc = new Scanner(System.in);
String st = sc.next();

You can use sc.nextInt() to get integer value from console.

2

Unless you are developing a very specific application, the Console object returned by System.console() is not the one you should use to retrieve user input.

This is System.console() definition:

 /**
 * Returns the unique {@link java.io.Console Console} object associated
 * with the current Java virtual machine, if any.
 *
 * @return  The system console, if any, otherwise <tt>null</tt>.
 *
 * @since   1.6
 */
 public static Console console() {
     if (cons == null) {
         synchronized (System.class) {
             cons = sun.misc.SharedSecrets.getJavaIOAccess().console();
         }
     }
     return cons;
 }

It may return null: Returns the unique object associated with the current Java virtual machine, if any.

Here you can find the reason why it can be null:

Whether a virtual machine has a console is dependent upon the underlying platform and also upon the manner in which the virtual machine is invoked. If the virtual machine is started from an interactive command line without redirecting the standard input and output streams then its console will exist and will typically be connected to the keyboard and display from which the virtual machine was launched. If the virtual machine is started automatically, for example by a background job scheduler, then it will typically not have a console.

As other answers and comments suggest, you should use System.in, being Scanner an easy to use tool to read lines and tokens.