0

I am building an application in Java (using NetBeans) that accepts user input through the console and prints out a statement using their name (given in user input). The following is the code:

package amazingpets;
import java.io.Console;

public class AmazingPets {

    public static void main(String[] args) {
        Console console = System.console();
        String firstName = console.readLine("What is your name? ");
        console.printf("My name is %s.\n",firstName);
    } 
}

However I keep getting the following error in the console:

Exception in thread "main" java.lang.NullPointerException
at amazingpets.AmazingPets.main(AmazingPets.java:14)
Java Result: 1

Can anyone please suggest a possible solution?

Elrond_EGLDer
  • 47,430
  • 25
  • 189
  • 180
MarcB1
  • 249
  • 1
  • 2
  • 7
  • 1
    When you post code and an exception with a line number in it, it is a bad idea to reformat the code. The Exception is triggered on line 14. Your posted code has less than 14 lines. Which line is the actual 14? – Erik Vesteraas May 23 '15 at 21:07

5 Answers5

2

From the documentation of System#console, it returns:

The system console, if any, otherwise null.

So your code is equivalent to:

String firstName = null.readLine("What is your name? ");

I would suggest you to use Scanner scanner = new Scanner(System.in); instead.

Maroun
  • 87,488
  • 26
  • 172
  • 226
0

When you run code in an IDE you will usually not have a console object. System.console() will thus return null and console.readLine("What is your name? "); will generate a NullPointerException. You can still read via System.in, so to read a line you can instead use:

Scanner sc = new Scanner(System.in);
String read = sc.nextLine();
Erik Vesteraas
  • 4,277
  • 1
  • 19
  • 34
0

System.console() returns a console if it exists. Java apps may be launched without a console.

Anywhy it seams this is a duplicate of this one (among others):

Why does System.console() return null for a command line app?

Hope it helps

Community
  • 1
  • 1
Leo Nomdedeu
  • 308
  • 2
  • 5
0

Use Scanner instead of Console
As mentioned in this answer this answer

Community
  • 1
  • 1
Ahd Radwan
  • 1,062
  • 3
  • 12
  • 29
0

Isn't line 14 where you create firstName variable? In this case console may be null. Javadoc for Console says

` a unique instance of this class which can be obtained by invoking theSystem.console() method. If no console device is available then an invocation of that method will return null.`