Answer the question
In order to leave comments, you need to log in
Why doesn't keyboard input work?
In Horstmann's book "Professional's Library" I came across a code for reading data from the keyboard, but when I try to run identical code on my computer, the compiler gives an error.
And now the question is: what is wrong in this code and how to fix it, or at least why in the line "Console consol = System.console();" console value becomes null?
Compiler error, close-up:
Answer the question
In order to leave comments, you need to log in
The console says that the error is in the HelloWorld file, line 8, NullPointerException .
They tell you that NPE happened :) . On line 7, System.console() returned NULL. On the eighth line, you are trying to access a variable that has a NULL value.
Try this example in another IDE or command line. It seems that for some reason there is no access to the console.
And don't get used to naming classes with a small letter :)
Well, firstly, the error is thrown not by the compiler, but by the JRE, i.e. runtime. And the error says that at the moment no console is associated with the running JVM.
To understand the cause of the error, you need to understand that the console may not necessarily be present, which, in fact, is written in the javadoc :
public static Console console()
Returns the unique Console object associated with the current Java virtual machine, if any.
Returns:
The system console, if any, otherwise null.
public class Test {
static java.util.Scanner scanner = new Scanner(System.in);
public static void main(String[] args) {
readLine("enter code:")
}
private String readLine(String prompt) {
System.out.println(prompt)
return scanner.nextLine()
}
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question