简单控制台测试应用程序中的NullPointerException
作者:互联网
这个问题已经在这里有了答案: > Trying to read from the console in Java 4个
> What is a NullPointerException, and how do I fix it? 12个
我刚开始学习一些Java,并编写了这个简单的程序,但是我不知道我的代码有什么问题.
这是我在运行时看到的错误:
Exception in thread “main” java.lang.NullPointerException
at 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.in和System.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);
标签:compiler-errors,ide,java 来源: https://codeday.me/bug/20191118/2026281.html