【问题标题】:NullPointerException in simple console test application [duplicate]简单控制台测试应用程序中的 NullPointerException [重复]
【发布时间】:2016-09-10 04:50:22
【问题描述】:

我刚开始学习一些 Java,并编写了这个简单的程序,但我不知道我的代码有什么问题。

这是我运行时看到的错误:

线程“main”中的异常 java.lang.NullPointerException 在 treehousejava.Main.main(Main.java:9)

这是我的代码:

package treehousejava;

import java.io.Console;

public class Main {
@SuppressWarnings("unused")
    public static void main (String[] args){
        Console console = System.console();
        String q = console.readLine("Hi there! what's your name? ");
        console.printf("hi there %s ! my name is console! ");
    }
}

【问题讨论】:

  • System.console 的 javadoc 说可能没有,在这种情况下它将返回 null。有充分的理由尝试使用控制台吗?如果没有,我会使用System.out.println 输出,ScannerSystem.in 输入。
  • @Unknown 这与这里无关。很清楚哪个变量为空,在这种情况下,问题是 为什么,而您建议的副本没有回答这个问题(尽管很容易回答,如 cmets 和答案所示)跨度>
  • 事实上,在Eclipse(我使用的IDE)中运行这样的程序会导致NPE,因为没有Console。不过,在命令行上运行会起作用。解决方案是不使用它。看看亚当的回答。
  • console.printf("hi there %s ! my name is console! "); 行中,%s 是字符串的占位符,但没有提供字符串。我怀疑你想使用console.printf("hi there %s ! my name is console! ", q);

标签: java compiler-errors ide


【解决方案1】:

我怀疑您想将System.inSystem.out 用于此类学习计划。 System.console() 可能在您的平台上不可用,调用将返回 null,因此会返回 NullPointException。标准输入和输出将始终可用。

Scanner scanner = new Scanner(System.in);
System.out.println("Hi there! what's your name? ");
String q = scanner.nextLine();
System.out.printf("hi there %s ! my name is console! ", q);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-10-08
    • 2011-05-12
    • 1970-01-01
    • 1970-01-01
    • 2019-08-17
    • 2020-09-29
    • 2012-07-09
    相关资源
    最近更新 更多