用户输入 Java
User Input Java
我正在 Java 中构建一个应用程序(使用 NetBeans),它通过控制台接受用户输入并使用他们的名字(在用户输入中给出)打印出一条语句。以下是代码:
package amazingpets;
import java.io.Console;
public class AmazingPets {
public static void main(String[] args) {
Console console = System.console();
String firstName = console.readLine("What is your name? ");
console.printf("My name is %s.\n",firstName);
}
}
但是我在控制台中不断收到以下错误:
Exception in thread "main" java.lang.NullPointerException
at amazingpets.AmazingPets.main(AmazingPets.java:14)
Java Result: 1
任何人都可以提出一个可能的解决方案吗?
当您 运行 在 IDE 中编写代码时,您通常不会有控制台对象。 System.console()
将因此 return null
而 console.readLine("What is your name? ");
将生成 NullPointerException
。您仍然可以通过 System.in
阅读,因此要阅读一行,您可以改用:
Scanner sc = new Scanner(System.in);
String read = sc.nextLine();
根据 System#console
的文档,它 returns:
The system console, if any, otherwise null
.
所以你的代码等同于:
String firstName = null.readLine("What is your name? ");
我建议您改用 Scanner scanner = new Scanner(System.in);
。
System.console() returns 控制台(如果存在)。 Java 应用程序可以在没有控制台的情况下启动。
无论如何它接缝这是这个(以及其他)的副本:
Why does System.console() return null for a command line app?
希望对您有所帮助
使用Scanner
代替Console
正如这个答案中提到的 this answer
第 14 行不是创建 firstName 变量的地方吗?在这种情况下,控制台可能为空。控制台的 Javadoc 说
` a unique instance of this class which can be obtained by invoking theSystem.console() method. If no console device is available then an invocation of that method will return null.`
我正在 Java 中构建一个应用程序(使用 NetBeans),它通过控制台接受用户输入并使用他们的名字(在用户输入中给出)打印出一条语句。以下是代码:
package amazingpets;
import java.io.Console;
public class AmazingPets {
public static void main(String[] args) {
Console console = System.console();
String firstName = console.readLine("What is your name? ");
console.printf("My name is %s.\n",firstName);
}
}
但是我在控制台中不断收到以下错误:
Exception in thread "main" java.lang.NullPointerException
at amazingpets.AmazingPets.main(AmazingPets.java:14)
Java Result: 1
任何人都可以提出一个可能的解决方案吗?
当您 运行 在 IDE 中编写代码时,您通常不会有控制台对象。 System.console()
将因此 return null
而 console.readLine("What is your name? ");
将生成 NullPointerException
。您仍然可以通过 System.in
阅读,因此要阅读一行,您可以改用:
Scanner sc = new Scanner(System.in);
String read = sc.nextLine();
根据 System#console
的文档,它 returns:
The system console, if any, otherwise
null
.
所以你的代码等同于:
String firstName = null.readLine("What is your name? ");
我建议您改用 Scanner scanner = new Scanner(System.in);
。
System.console() returns 控制台(如果存在)。 Java 应用程序可以在没有控制台的情况下启动。
无论如何它接缝这是这个(以及其他)的副本:
Why does System.console() return null for a command line app?
希望对您有所帮助
使用Scanner
代替Console
正如这个答案中提到的 this answer
第 14 行不是创建 firstName 变量的地方吗?在这种情况下,控制台可能为空。控制台的 Javadoc 说
` a unique instance of this class which can be obtained by invoking theSystem.console() method. If no console device is available then an invocation of that method will return null.`