Reputation: 549
I have tried code:
import java.io.Console;
public class Default
{
public static void main(String args[]) throws IOException
{
Console console = System.console();
String testing = console.readLine("Enter Name: ");
System.out.println("Entered Name: "+ testing);
}
}
goes to exception with following error:
Source not found. NullPointerException
I am using Eclipse Juno EE for debugging .. !
And the reference link for above written code is here
Upvotes: 8
Views: 12108
Reputation: 96
The cause of this problem has already been mentioned in other answers, but I would like to add one possible solution.
There is a library that can be used as a replacement for java.io.Console
that mitigates the problem: https://codeberg.org/marc.nause/console-with-fallback
Upvotes: 0
Reputation: 1
import java.io.*;
public class ConsoleExTest {
public static void main(String[] args) throws Exception {
Console c = System.console();
String uname = c.readLine("User Name:");
char[] pwd = c.readPassword("Password:");
String upwd = new String(pwd);
if (uname.equals("chenna") && upwd.equals("chenna")) {
System.out.println("User is valid");
} else {
System.out.println("User is not valid");
}
}
}
Note:
System.console();
return null so we will get
Upvotes: 0
Reputation: 864
Are you running your program from an ide as console.readLine
returns null
when used from an IDE.
For more details refer to this
If you run it from command line you will not get this error.
Upvotes: 6
Reputation: 12154
That is because, IDE is not using console !
Go to cmd.exe
type cd <bin path>
hit enter..
now type java <classname>
hit enter
It works!
Upvotes: 3
Reputation: 4568
System.console()
returns null if there is no console.
You can work round this either by adding a layer of indirection to your code or by running the code in an external console and attaching a remote debugger.
Upvotes: 3