开发者

What causes this NullPointerException in my Java program?

import java.io.*;
public class listjava
{
   public static void main(String args[]){
       Console c = System.console();
       char[] pw;
       pw = c.readPassword("%s","pw: ");
    开发者_如何学运维   for (char ch: pw)
           c.format("%c ",ch);
       c.format("\n");

       MyUtility mu = new MyUtility();
       while(true)
       {
           String name = c.readLine("%s","input?: ");
           c.format("output : %s \n",mu.doStuff(name));
       }
    }
}

class MyUtility{
    String doStuff (String arg1){
        return " result is " + arg1;
    }
}

I got an error like this:

Exception in thread "main" java.lang.NullPointerException
   at listjava.main(listjava.java:7)

Why is my program wrong?


System.console() is returning null.

Quoting Java's documentation:

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

So, there are probably no console associated to your JVM. You are probably running your program within Eclipse or other IDE. Try running your program from your system's command line. It should work.

To run your program from the command line.

  1. Go to directory where listjava.class resides
  2. Run java's interpreter

    $ java listjava


According to the Javadoc for System.console():

Returns: The system console, if any, otherwise null.

So I suppose that System.console() is handing back null and your line

pw = c.readPassword("%s","pw: ");

is therefore dereferencing null. I'm not sure what fix you might want to use; perhaps reading from System.in instead?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜