Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Java Java Basics Using your New Tools Multiple Strings

Getting a Null pointer exception, even though I am using the same code as the teacher.

public class Main { public static void main(String[] args) {

    Console console = System.console();

    String name = console.readLine("Enter your name:  ");
    String adjective = console.readLine("Enter an adjective  ");
    console.printf("%s is very %s", name, adjective);

error: Exception in thread "main" java.lang.NullPointerException at com.teamtreehouse.Main.main(Main.java:16)

Emmanuel C
Emmanuel C
10,636 Points

Are you running this in workspace or a separate IDE?

2 Answers

Emmanuel C
Emmanuel C
10,636 Points

Hey Mike,

This has to do with how you run the program. System.console() will return the console that is connected with it. The command line is itself a console, so when you run it from there that console will be automatically connected and thats what returns from System.console().

However if you run the program from an IDE, like IntelliJ the console will not connect automatically therefore that System.console() will return null. Which causes that error when you try to readLine() from it. To accomplish the same task from an IDE, you can use the scanner class, try...

import java.util.Scanner;

public static void main(String[] args) {
    Scanner scanner = new Scanner(System.in);

    System.out.print("Enter you name: ");
    String name = scanner.nextLine();

    System.out.print("Enter an adjective: ");
    String adjective = scanner.nextLine();

    System.out.printf("%s is very %s", name, adjective);
}

Alternatively if you run your code from the command line like how its done in the lesson with workspace, itll work

Thanks

Intelli J