A
A
arsenii112015-03-12 23:06:30
Java
arsenii11, 2015-03-12 23:06:30

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. 35d2636eda894718a7794cca698f4c0b.png
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:bfde398b374e4ce1908aa3ca2f748c82.png

Answer the question

In order to leave comments, you need to log in

4 answer(s)
I
IceJOKER, 2015-03-12
@IceJOKER

The console says that the error is in the HelloWorld file, line 8, NullPointerException .

T
Timur, 2015-03-13
@timych

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 :)

Z
zed_the_dead, 2015-03-15
@zed_the_dead

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.

If you run the same code manually via cmd (or sh) - everything will work. When launched from Intellij Idea, the console is not associated. If you need it to work this way and that, you can use java.util.Scanner as a workeround, setting it on System.in, you can even add your own method with a string for output:
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()
    }
}

I haven't tested the code, but the principle should be clear.

E
exenza, 2015-03-17
@exenza

There was such a ticket on jetbrains. They advised to create a launcher to launch the console. Comment

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question