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 trialRanjen Naidu
2,474 Pointshaving problem in solving NullPointerExecption error
I am receiving this error for my code in workspace
Exception in thread "main" java.lang.NullPointerException
at Game.getCurrentProgress(Game.java:25)
at Prompter.displayProgress(Prompter.java:18)
at Hangman.main(Hangman.java:5)
The code are as below in the comment
Ranjen Naidu
2,474 Pointsimport 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("Enter a letter: ");
char guess = guessAsString.charAt(0);
return mGame.applyGuess(guess);
}
public void displayProgress(){
System.out.printf("Try to solve: %s\n", mGame.getCurrentProgress());
}
}
Ranjen Naidu
2,474 Pointspublic class Game{
private String mAnswer;
private String mHit;
private String mMisses;
public Game (String answer){
mAnswer = answer;
}
public boolean applyGuess(char letter){
boolean isHit = mAnswer.indexOf(letter) >= 0;
//if indexOf value is -1 meaning the char is not existed in the string.
if(isHit){
mHit += letter;
}else{
mMisses += letter;
}
return isHit;
}
public String getCurrentProgress(){
String progress = "";
for(char letter : mAnswer.toCharArray()){
char display = '-';
if (mHit.indexOf(letter) >= 0){
display = letter;
}//if
progress += display;
}//for
return progress;
}//getCurrentProgress method
}
2 Answers
Craig Dennis
Treehouse TeacherLooks like you forgot to initialize your mHit
and mMisses
to empty strings in the Game constructor.
Hope it helps!
Ranjen Naidu
2,474 PointsYes it works . Thanks I missed out initialization as you said.
public Game (String answer){
mAnswer = answer;
mHit = "";
mMisses="";
}
Ranjen Naidu
2,474 PointsCan i assume , each time i received NullPointerExecption error , it means i missed out initialization in my constructor ? Are they any other way we will confront with this error ?
Craig Dennis
Treehouse TeacherAnytime you try to access an uninitialized variable a NullPointerException
will happen. We will go over null
and all the fun it brings in an upcoming course.
Ranjen Naidu
2,474 PointsRanjen Naidu
2,474 Points