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 Objects (Retired) Creating the MVP Prompting for Guesses

Stephanie Owens
Stephanie Owens
622 Points

Null Pointer Exception error

I've done the code exactly as written in the video (below) but I am getting the error:

Exception in thread "main" java.lang.NullPointerException
    at Prompter.promptForGuess(Prompter.java:17)
    at Hangman.main(Hangman.java:9)

A google search of this error pulled up a bunch of answers I don't really understand.
Does this have something to do with the fact that I am working with Eclipse and not the same program as is being used in the videos?

public class Hangman {
  public static void main(String[] args) {
    Game game = new Game("treehouse");
    Prompter prompter = new Prompter (game);
    boolean isHit = prompter.promptForGuess();
    if (isHit) {
      System.out.println("We got a hit!!");
    } else {
      System.out.println("Whoops! that was a miss!");
    }
  }
}
import java.io.Console;

public class Prompter {
  private Game mGame;
  public Prompter (Game game) {
    mGame = game;
  }
  public boolean promptForGuess() {
    Console console = System.console();
    String guessAsString = console.readLine(null, "Enter a letter: ");
    char guess = guessAsString.charAt(0);
    return mGame.applyGuess(guess);
  }
}
public class Game {
  private String mAnswer;
  private String mHits;
  private String mMisses;

  public Game(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;
  }
}

2 Answers

Craig Dennis
STAFF
Craig Dennis
Treehouse Teacher

Yes Eclipse has a hard time working with the java.io.Console If you want to run Eclipse you can run the program from the command prompt (terminal (Mac) / PowerShell (Windows) ) instead of using the wrapped Eclipse environment.

Sorry for the inconvenience! The next course will run in Eclipse without changing anything.

Nino Roldan
PLUS
Nino Roldan
Courses Plus Student 9,308 Points

Thanks for letting us know. Somehow my Workspace is acting up so I thought of doing the exercises in Eclipse. Will try doing it via the Windows console instead.