这是我的代码:
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();
}