0

Summary 1. I am import java.io.console,i am not getting any error in my code, code is correct, I thought, It's getting some error in eclipse software... Error :

Exception in thread "main" java.lang.NullPointerException   at
loops.Escapey.main(Escapey.java:9)

Coding:

package loops;

import java.io.Console;
public class Escapey {
public static void main(String[] args) {

    Console ar = System.console(); // creating a new object for console

    String name = ar.readLine("how old are you ?"); //reads a user input 
    System.out.printf("%s - pretty age",name);
}
}

Ouput : - I except the output how old are you ?? 18 18 - pretty age But the actual output is getting error... Exception in thread "main" java.lang.NullPointerException at loops.Escapey.main(Escapey.java:9)

Micheal
  • 11
  • 4

2 Answers2

0

I assume you are running this into some IDE. Since System.console returns the attached console, if you run it into IDE, it will return NULL. The better approach is to use Scanner class. If you really want to use System.console, you will have to test it on some console. If on Mac, run the terminal. On Linux any of the terminal apps would work.

vavasthi
  • 922
  • 5
  • 14
0

If we run this in IDE (Intellij), it is throwing null pointer exception. Since this is related to console, I tried to execute this in command line and it works fine.

Execute these steps in terminal or command line and it will work

1) javac Escapey.java
2) java Escapey
Praveen E
  • 926
  • 8
  • 14