This question already has answers here:
Trying to read from the console in Java

(4个答案)



What is a NullPointerException, and how do I fix it?

(12个答案)


4年前关闭。




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

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



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

关于java - 简单控制台测试应用程序中的NullPointerException ,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/39422676/

10-10 12:53
查看更多