java - System.console() 空指针异常

标签 java

<分区>

这是我的代码:

System.out.println("Enter Username: ");
String unm=System.console().readLine();

System.out.println("Enter Password: ");
char[] pwd=System.console().readPassword();

System.out.println("Welcome: " + "" + " Your password is " + new String(pwd));

为什么会出现此错误?

Enter Username:

Exception in thread "main" java.lang.NullPointerException at Cons.main(Cons.java:13)

最佳答案

来自 Javadoc:

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

如果没有与 JVM 关联的控制台,则指向的行是对空对象的方法调用,因此是异常。

您如何启动您的应用程序?

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.

如果你想从标准输入中读取用户名,你可以使用这个代码:

try {
    System.out.print("Enter Username: ");
    InputStreamReader streamReader = new InputStreamReader(System.in);
    BufferedReader bufferedReader = new BufferedReader(streamReader);
    String username = bufferedReader.readLine();
} catch (IOException e) {
    e.printStackTrace();
}

关于java - System.console() 空指针异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34555185/

相关文章:

java - 获取 JTable 以打印表格格式

Java 和 Selenium 陈旧元素错误

Java - 两个线程不同步

java - 在 hibernate 中如何以编程方式设置事务的隔离级别,或者如何创建两个具有不同隔离级别的事务

java - 在 JFrame 上绘制图像的最简单方法?

java - Guava - 如何根据谓词从列表中删除,跟踪删除的内容?

java - Spring data rest - 处理实体验证

参数为 “List<Class<? extends Object>>”的Java方法

java - ANTLR BNF 语法符号中 epsilon 的等价物是什么?

java - 使用相同的作业 ID 调度不同的 crontimers