System.console() gives NullPointerException in NetBeans

本秂侑毒 提交于 2019-12-17 16:49:34

问题


I'm absolutely new in Java.

I have the following problem: method readLine() or nextLine(), nextInt() etc. throw an exception: NullPointerException.

I use NetBeans IDE(if it matters).

public static void Reading()
{

    String qq;
    qq = System.console().readLine();
    System.console().printf(qq);
}

回答1:


Some IDEs don't provide a console. Note that System.console() returns null in these cases.

From the documentanion

Returns:

     The system console, if any, otherwise null.

You can always use System.in and System.out instead, as follows:

String qq;
Scanner scanner = new Scanner(System.in);
qq = scanner.nextLine();
System.out.println(qq);



回答2:


Two things:

  1. The standard way of printing things is System.out.println("Thing to print");
  2. The standard way of reading input off the console is: Scanner s = new Scanner(System.in); String input = s.nextLine();

So with these in mind, your code should be

public static void Reading() {
    String qq;
    Scanner s = new Scanner(System.in);
    qq = s.nextLine();
    System.out.println(qq);
    s.close();
}

or

public static void Reading() {
    String qq;
    try (Scanner s = new Scanner(System.in)) {
        qq = s.nextLine();
        System.out.println(qq);
    }
}


来源:https://stackoverflow.com/questions/26078106/system-console-gives-nullpointerexception-in-netbeans

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!