MarcB1
MarcB1

Reputation: 249

User Input Java

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?

Upvotes: 0

Views: 352

Answers (5)

Erik Vesteraas
Erik Vesteraas

Reputation: 4735

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

Upvotes: 0

Sergey Maksimenko
Sergey Maksimenko

Reputation: 588

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

Upvotes: 0

Ahd Radwan
Ahd Radwan

Reputation: 1100

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

Upvotes: 0

Leo Nomdedeu
Leo Nomdedeu

Reputation: 338

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

Upvotes: 0

Maroun
Maroun

Reputation: 96018

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.

Upvotes: 2

Related Questions