I am trying to use Console class to get input from user but a null object is returned when I call System.console()
. Do I have to change anything before using System.console?
Console co=System.console();
System.out.println(co);
try{
String s=co.readLine();
}
The following takes athspk's answer and makes it into one that loops continually until the user types "exit". I've also written a followup answer where I've taken this code and made it testable.
Example output:
Using Console to read input(usable only outside IDE):
Another way(works everywhere):
System.console() returns null in an IDE
so if you really need to use System.console(), read this solution from McDowell.
Use System.in
http://www.java-tips.org/java-se-tips/java.util/how-to-read-input-from-console.html
I wrote the Text-IO library, which can deal with the problem of System.console() being null when running an application from within an IDE.
It introduces an abstraction layer similar to the one proposed by McDowell. If System.console() returns null, the library switches to a Swing-based console.
In addition, Text-IO has a series of useful features:
Usage example:
In this image you can see the above code running in a Swing-based console.
Try this. hope this will help.