Win a copy of Kotlin in Action this week in the Kotlin forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

Console  RSS feed

 
ahmad tamimi
Greenhorn
Posts: 5
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi All
Im trying to run the following code from SCJP Sun Certified Programmer for Java 6 Sierra book but i get NullPointer Exception at line 7(pw=c.rearPassword...)
this is the code:


package scjp;
import java.io.Console;
public class ConsoleTest2 {
public static void main(String[] args) {
Console c = System.console(); // #1: get a Console
char[] pw;
pw = c.readPassword("%s", "pw: "); // #2: return a char[]
for(char ch: pw)
c.format("%c ", ch); // #3: format output
c.format("\n");
MyUtility mu = new MyUtility();
while(true) {
String name = c.readLine("%s", "input?: "); // #4: return a String
c.format("output: %s \n", mu.doStuff(name));
}
}
}
class MyUtility { // #5: class to test
String doStuff(String arg1) {
// stub code
return "result is " + arg1;
}
}

im using eclipse to run the code, so should i enable anything to allow input,because it seems that i'm trying to use pw and it is null.
 
Rob Spoor
Sheriff
Posts: 21088
85
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
System.console() returns null if the program is invoked from anywhere but an actual command prompt. When run using javaw or an IDE (like Eclipse) you simply don't get access to Console. You'll need to go command line.

And please, next time UseCodeTags.
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!