【问题标题】: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.in 和System.out,如下所示:
String qq;
Scanner scanner = new Scanner(System.in);
qq = scanner.nextLine();
System.out.println(qq);
【解决方案2】:
两件事:
- 打印东西的标准方式是
System.out.println("Thing to print");
- 从控制台读取输入的标准方法是:
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);
}
}