Question:
Java console.readLine()?
chris_02181987
2007-12-26 19:18:16 UTC
Code
*************************************************************
import java.io.Console;

public class Pswd
{
public static void main(String[] args)
{
Console cons = System.console();

String usr =cons.readLine("UsrName: ");
char [] pswd = cons.readPassword("Password: ");

System.out.println(usr);

for(Character c:pswd)
System.out.print(c);
}
}
*********************************************************
output

----jGRASP exec: java Pswd

Exception in thread "main" java.lang.NullPointerException
at Pswd.main(Pswd.java:9)

----jGRASP wedge2: exit code for process is 1.
----jGRASP: operation complete.
***********************************************
Suggestion Please
Four answers:
Drew F
2007-12-26 19:35:42 UTC
A quick check of java.sun.com APIs, we see:



"System.console()



Returns the unique Console object associated with the current Java virtual machine, if any.



Returns:

The system console, if any, otherwise null."



Apparently, your JVM does not have a system console. Adjust your code to read:



Console cons = System.console();

if ( cons == null ) {

System.err.println( "No Console found." );

System.exit( 1 );

}





The online docs continue to say:



"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. "
Erika
2016-10-13 12:22:25 UTC
Java Console Readline
msaeed33
2007-12-26 23:10:12 UTC
As other said, jGRASP doesn't provide a console to the jvm, hence the null pointer exception.



Also, please note that println actually accepts char[], so you can replace the last for loop with simply

System.out.println(pswd);
demiser55
2007-12-26 19:26:33 UTC
http://mindprod.com/jgloss/compileerrormessages.html


This content was originally posted on Y! Answers, a Q&A website that shut down in 2021.
Loading...