Java控制台API
我尝试使用eclipse的 java.io.Console
API。我的示例代码如下。
I tried the java.io.Console
API using eclipse. My sample code follows.
package app;
import java.io.Console;
public class MainClass {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Console console = System.console();
console.printf("Hello, world!!");
}
}
当我尝试运行示例时,我收到以下错误。
When I tried running the example, I got the following error.
线程main中的异常
java.lang.NullPointerException at
app。 MainClass.main(MainClass.java:11)
Exception in thread "main" java.lang.NullPointerException at app.MainClass.main(MainClass.java:11)
我在哪里错了?感谢。
由于您在评论中提到您使用Eclipse,因此目前没有支持 控制台
,根据此错误报告。
Since you've mentioned in a comment that you're using Eclipse, it appears that there is currently no support for Console
in Eclipse, according to this bug report.
System.console
方法返回与当前Java虚拟机关联的控制台,如果没有控制台,它将返回 null
。从 System.console
方法的文档:
返回唯一控制台与当前Java
虚拟机相关联的对象。
Returns the unique
Console
object associated with the current Java virtual machine, if any.
strong>
Returns:
系统控制台(如果有),否则 null
。
The system console, if any, otherwise null
.
不幸的是,这是正确的行为。您的代码中没有错误。唯一的改进是对 Console
对象执行 null
检查,看看是否有返回或不;这将通过尝试使用不存在的控制台
对象来防止 NullPointerException
。
Unfortunately, this the correct behavior. There is no error in your code. The only improvement that can be made is to perform a null
check on the Console
object to see if something has been returned or not; this will prevent a NullPointerException
by trying to use the non-existent Console
object.
例如:
Console c = System.console();
if (c == null) {
System.out.println("No console available");
} else {
// Use the returned Console.
}