2

I just started learning some Java and I made this simple program but I dont know whats wrong with my code.

This is what the error I see when I run:

Exception in thread "main" java.lang.NullPointerException at treehousejava.Main.main(Main.java:9)

This is my code:

package treehousejava;

import java.io.Console;

public class Main {
@SuppressWarnings("unused")
    public static void main (String[] args){
        Console console = System.console();
        String q = console.readLine("Hi there! what's your name? ");
        console.printf("hi there %s ! my name is console! ");
    }
}
Adam
  • 35,919
  • 9
  • 100
  • 137
  • 2
    The javadoc for `System.console` says that there might not be one, in which case it will return `null`. Is there a good reason to try to use the console? If not, I'd just use `System.out.println` for output and `Scanner` on `System.in` for input. – ajb Sep 10 '16 at 04:55
  • 2
    @Unknown That's not relevant here. It is clear which variable is null, the question is *why* in this case, and that isn't answered by your suggested duplicate (although it's easy to answer, as shown by the comments and answers) – Erwin Bolwidt Sep 10 '16 at 05:09
  • In fact, running such a program in Eclipse (the IDE I use) results in an NPE, because there is no `Console`. Running on command line will work, though. The solution is to not use it. Look at Adam's answer. – Seelenvirtuose Sep 10 '16 at 05:41
  • In the line `console.printf("hi there %s ! my name is console! ");`, the `%s` is a placeholder for a string, but no string is provided. I suspect you want to use `console.printf("hi there %s ! my name is console! ", q);`. – Curtis Lusmore Sep 10 '16 at 05:42
  • Also: [System.console() returns null](http://stackoverflow.com/questions/4203646/system-console-returns-null) –  Sep 10 '16 at 05:48

1 Answers1

2

I suspect you want to use System.in and System.out for this type of learning program. System.console() might not be available on your platform and the call will return null, hence the NullPointException. Standard input and output will always be available.

Scanner scanner = new Scanner(System.in);
System.out.println("Hi there! what's your name? ");
String q = scanner.nextLine();
System.out.printf("hi there %s ! my name is console! ", q);
Adam
  • 35,919
  • 9
  • 100
  • 137