【问题标题】:System.console() gives a NullPointerException in NetBeansSystem.console() 在 NetBeans 中给出 NullPointerException
【发布时间】:2014-09-27 19:01:59
【问题描述】:

我遇到以下问题:方法readLine()nextLine()nextInt()等抛出异常:NullPointerException

我使用NetBeans IDE(如果重要的话)。

public static void Reading()
{
    String qq;
    qq = System.console().readLine();
    System.console().printf(qq);
}

【问题讨论】:

    标签: java exception netbeans nullpointerexception console


    【解决方案1】:

    某些 IDE 不提供控制台。请注意,System.console() 在这些情况下会返回 null

    来自the documentanion

    返回:

         系统控制台(如果有),否则为空。

    您始终可以改用System.inSystem.out,如下所示:

    String qq;
    Scanner scanner = new Scanner(System.in);
    qq = scanner.nextLine();
    System.out.println(qq);
    

    【讨论】:

    • 哦。看起来这就是问题所在。非常感谢!
    【解决方案2】:

    两件事:

    1. 打印东西的标准方式是System.out.println("Thing to print");
    2. 从控制台读取输入的标准方法是:Scanner s = new Scanner(System.in); String input = s.nextLine();

    所以考虑到这些,你的代码应该是

    public static void Reading() {
        String qq;
        Scanner s = new Scanner(System.in);
        qq = s.nextLine();
        System.out.println(qq);
        s.close();
    }
    

    public static void Reading() {
        String qq;
        try (Scanner s = new Scanner(System.in)) {
            qq = s.nextLine();
            System.out.println(qq);
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-02-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多