java空指针异常问题,新人求教

flyence 2011-08-08 11:56:44
先上代码
import java.io.*;
public class Test{
public static void main(String[] args) {

while(true){
char[] password = System.console().readPassword();
System.out.println(password);

}
}
}
主要是测试console类中的readPassword方法。
在eclipse中。会出现java.lang.NullPointerException,即空指针异常,应该是由于console控制台引起的,但为什么用javac,java在命令提示符中编译的时候木有一点问题? 求教
...全文
199 9 打赏 收藏 转发到动态 举报
写回复
用AI写文章
9 条回复
切换为时间正序
请发表友善的回复…
发表回复
linfeng266 2011-08-09
  • 打赏
  • 举报
回复
学到东西了.
ctwoz 2011-08-09
  • 打赏
  • 举报
回复
我们老师也说过,那个只能在命令行下运行,在Eclipse下无法得到console…
daijope 2011-08-09
  • 打赏
  • 举报
回复
我的eclipse也是不行啊,,
liuhuanleijava 2011-08-09
  • 打赏
  • 举报
回复
mark!
walkman_22 2011-08-09
  • 打赏
  • 举报
回复
没看明白,路过。
蓝阳 2011-08-08
  • 打赏
  • 举报
回复
找到我上面说的那个所谓的正规说法了:
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.”

同样是在CSDN论坛中哦:http://topic.csdn.net/u/20090211/13/f4032ae4-b18e-4ea3-90cf-f18a1604fc75.html
蓝阳 2011-08-08
  • 打赏
  • 举报
回复
偶是新人噢~
如果你在你主函数代码中加入以下代码,在Eclipse下运行会输出“sales: unable to obtain console”的:
Console console = System.console();
if (console == null) {
System.err.println("sales: unable to obtain console");
return;
}
这就说明虚拟机在Eclipse下运行的时候是没有控制台console的。
我记得有一个正规的说法:当Java程序如果是从cmd命令行中运行的话,而且标准输入/出流没有被重定向过时console是存在的;但是当Java虚拟机是自动启动的,就不存在控制台。我估计Eclipse它作为一个IDE就是以后者的方式启动虚拟机,所以运行Java程序的时候不存在控制台。

个人猜测成分较多T-T,坐等真相~
qybao 2011-08-08
  • 打赏
  • 举报
回复
参考javadoc说明
console
public static Console console()
Returns the unique Console object associated with the current Java virtual machine, if any.

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

说明在eclipse里运行的时候,System.console()返回了null
把程序改一下看看是不是真的返回null
Console c = System.console();
if (c != null) {
char[] password = c.readPassword();
System.out.println(password);
} else {
System.out.println("null");
}
beiouwolf 2011-08-08
  • 打赏
  • 举报
回复
Eclipse的那个console标签,只能用System.in流来读

62,612

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧