-
Console input issue
Hi, I'm writing something that uses input from the console, I'm using SE6.
My problem code is the following:
Code:
Console c = System.console();
String number = c.readLine("Number? ");
The problem is that when I compile using the terminal it works as expected and the 'readLine' prompts the user.
When I run it using Eclipse IDE it produces a NullPointerException on the first line. The project has the same java compiler as what I'm using in the terminal.
What could be wrong?
Thanks.
-
Quote:
What could be wrong?
Running it in Eclipse.
As the Console API docs state: "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 this virtual machine has a console then it is represented by a unique instance of this class which can be obtained by invoking the System.console() method. If no console device is available then an invocation of that method will return null."
Perhaps Eclipse offers some way of running the program outside it's own "Console" environment. (But in that case you would lose the Goodness of being able to click on lines in runtime exceptions etc.)
-
I recommend using a Scanner like so:
Code:
Scanner s=new Scanner(System.in);
-
There may be a problem with Eclipse and the Console class. Per Console API:
"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.
If this virtual machine has a console then it is represented by a unique instance of this class which can be obtained by invoking the System.console() method. If no console device is available then an invocation of that method will return null."
So if you check for a Console object and it doesn't exist, if it is null, you can't use it.