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 Creating the MVP Prompting for Guesses

Getting a java.lang.NullPointerException

I've tried following the video to a T, but somehow I managed to screw up parts of the code that I have no idea where. I've tried going through the video a few times, pinpointing where's the fault in my code but no avail.

Exception in thread "main" java.lang.NullPointerException
at Game.applyGuess(Game.java:15)
at Prompter.promptForGuess(Prompter.java:16)
at Hangman.main(Hangman.java:9)

This is the code:

Hangman.java
public class Hangman {

  public static void main(String[] args) {
    // Your incredible code goes here...
    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("Oops missed"); 
    }
  }
}
Game.java
class Game{
    private String answer;
    private String hits;
    private String misses;



    public Game(String anwer) {
      this.answer = answer;
      hits="";
      misses="";
    }

    public boolean applyGuess(char letter) {
      boolean isHit = answer.indexOf(letter) != -1;
      if (isHit) {
        hits += letter; 
      } else {
        misses += letter; 
      }
      return isHit;
    }

}
Prompter.java
import java.util.Scanner;

class Prompter {

  private Game game;

  public Prompter(Game game) {
    this.game = game;
  }

  public boolean promptForGuess() {
    Scanner scanner = new Scanner(System.in);
    System.out.print("Enter a letter:  ");
    String guessInput = scanner.nextLine();
    char guess = guessInput.charAt(0);
    return game.applyGuess(guess);
  }



} 

1 Answer

Hi there,

I changed one thing in your code:

public Game(String anwer) 

to

public Game(String answer) 

Your null pointer was coming from:

this.answer = answer;

As you passed in a variable named anwer not answer so it couldn't be assigned.

Steve.