Java控制台API [英] Java console API

查看:170
本文介绍了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 方法的文档:


返回唯一< c $ c>控制台与当前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.
}

这篇关于Java控制台API的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆