0

I have been reading the possible solutions to this error, but I don't quite understand it, here is the code and the output it gives me:

import java.io.Console;

public class Ejercicio3 {

    public static void main(String[] args) {

        Console c = System.console();

        System.out.println("¿Cuántas puertas quieres que tenga el coche?"); 
        String numPuertas = c.readLine(); /* Here is the error */
        int numNum = Integer.parseInt(numPuertas);

        if (numNum == 3) {
            System.out.println("Es un coche deportivo");
        } 

        else if (numNum == 5) {
            System.out.println("Es un coche familiar");
        }
    
        else {
            System.out.println("¿Seguro que el coche tiene " + numNum + " puertas?");
        }
    
    }
}

Output

¿Cuántas puertas quieres que tenga el coche?
Exception in thread "main" java.lang.NullPointerException: Cannot invoke "java.io.Console.readLine()" because "<local1>" is null
at Ejercicio3.main(Ejercicio3.java:13)

But it won't let me answer the question

SomethingSomething
  • 11,491
  • 17
  • 68
  • 126
  • 1
    Check the docs [here](https://docs.oracle.com/javase/7/docs/api/java/lang/System.html#console()). It appears that you have no console, which makes `System.console()` return null. Do you use `javaw` to run your app? You should use `java` rather than `javaw` to have a console. The fact that you try to call a method of `c` while it is assigned with `null` causes the `NullPointerException`. – SomethingSomething Jun 06 '22 at 08:36
  • 1
    Does this answer your question? [System.console() returns null](https://stackoverflow.com/questions/4203646/system-console-returns-null). Search for more. – Ole V.V. Jun 06 '22 at 09:17

1 Answers1

1

Before using the instance returned by Console cons = System.console() to call the method, check whether the instance cons is null before executing other processes.

If your Java program wants to interact with cmd under Windows or Terminal under Linux/unix, you can use this Java Console class to do it for you. Starting an application from such an interactive command line returns an available Console instance.

Java.io.Console can only be used in the original console where the standard input and output streams are not redirected, it is not available in Eclipse / Idea or other IDE consoles.

Ian
  • 1,198
  • 1
  • 5
  • 15