System.console () provides NullPointerException in NetBeans
I am completely new to Java.
I have the following problem: method readLine()
or nextLine()
, nextInt()
etc. throws an exception: NullPointerException
.
I am using NetBeans IDE (if it matters).
public static void Reading()
{
String qq;
qq = System.console().readLine();
System.console().printf(qq);
}
source to share
Some IDEs do not provide a console. Note what System.console()
returns null
in these cases.
From the doc
Return:
The system console, if present, is zero otherwise.
You can always use System.in
and System.out
, namely:
String qq;
Scanner scanner = new Scanner(System.in);
qq = scanner.nextLine();
System.out.println(qq);
source to share
Two things:
- The standard way to print things is
System.out.println("Thing to print");
- The standard way to read input from the console is:
Scanner s = new Scanner(System.in); String input = s.nextLine();
So, with that 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);
}
}
source to share