System.console()在NetBeans中提供NullPointerException
我是Java的新手。
我有以下问题:方法readLine()
或nextLine()
, nextInt()
等抛出exception: NullPointerException
。
我使用NetBeans IDE(如果重要的话)。
public static void Reading() { String qq; qq = System.console().readLine(); System.console().printf(qq); }
某些IDE不提供控制台。 请注意,在这些情况下, System.console()
返回null
。
来自文件
返回:
系统控制台(如果有),否则为null。
您可以始终使用System.in
和System.out
,如下所示:
String qq; Scanner scanner = new Scanner(System.in); qq = scanner.nextLine(); System.out.println(qq);
两件事情:
- 打印东西的标准方法是
System.out.println("Thing to print");
- 从控制台读取输入的标准方法是:
Scanner s = new Scanner(System.in); String input = s.nextLine();
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); } }