Console login error java.lang.NullPointerException

I tried the 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);
    }
}

      

jumps to the exception with the following error:
Source not found. NullPointerException

I am using Eclipse Juno EE for debugging ..!

The link for the above code is here

+7


source to share


4 answers


You are running your program from ide as it console.readLine

returns a value null

when used from the IDE.

For more details refer to this



If you run it from the command line, you will not receive this error.

+5


source


System.console()

returns null if there is no console.



You can work around this by either adding a layer of indirection to your code, or running the code in an external console and with a remote debugger .

+3


source


This is because the IDE does not use the console!

Go to cmd.exe

type cd <bin path>

press enter ..

now type java <classname>

hit enter

It works!

+3


source


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");
        }
    }

}

      

Notes:

System.console();

return zero, so we get

0


source







All Articles