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?

1
  • 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? Commented May 23, 2015 at 21:07

5 Answers 5

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.

Sign up to request clarification or add additional context in comments.

Comments

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

Comments

0

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

Comments

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.`

Comments

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();

2 Comments

In that case, can you please suggest possible solutions for acquiring Input in the IDE?
Apparantly System.in should still work in NetBeans specifically. So for example new Scanner(System.in) should work.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.