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

Problem java.langNullPointerException

Hi, I have a problem at the moment that I run the program. It sends me:

Exception in thread "main" java.lang.NullPointerException at PrompterHangman.promptForGuess(PrompterHangman.java:16) at mainHangman.main(mainHangman.java:17)

Looking in my code I see that the problem is with the line:

String guessAsString = console.readLine("Enter a letter: ");

I already imported the package java.io.Console, but I don´t fin the problem yet! I hope you can help me!

I attached all my code!

Regards.

import java.io.Console;

public class mainHangman {

    public static void main(String[] args) {

        GameHangman       game       = new GameHangman("treehouse");
         PrompterHangman prompter = new PrompterHangman(game);

        boolean isHit = prompter.promptForGuess();

        if (isHit) {
            System.out.println("We got a hit");
        } else {
            System.out.println("That was a miss");
        }
    }
}
import java.io.Console;

public class PrompterHangman {

    private GameHangman mGame;

    public PrompterHangman(GameHangman game) {
        mGame = game;
    }

    public boolean promptForGuess() {

        Console console = System.console();

        String guessAsString = console.readLine("Enter a letter: ");
        char    guess               = guessAsString.charAt(0);

        return mGame.applyGuess(guess);
    }
}
public class GameHangman {

    private String mAnswer;
    private String mHits;
    private String mMisses;

    public GameHangman(String answer) {
        mAnswer = answer;
        mHits   = "";
        mMisses = "";
    }

    public boolean applyGuess(char letter) {

        boolean isHit = mAnswer.indexOf(letter) >= 0;
        if (isHit) mHits   += letter;
        else       mMisses += letter;
        return  isHit;
    }
}

1 Answer

If the console isn't available, then reading from it will return null. Apparently this can happen in some environments, such as Eclipse:

http://stackoverflow.com/a/17992725

Craig Dennis
Craig Dennis
Treehouse Teacher

If you compile this locally on your machine you will be able to run it from the command line as well.

Thank you so much guys! It was so helpful!