I’m programming a traditional hangman game in Java. What I’m currently stuck on is to find if the users character input is not a character within the String.
if(getLetters.indexOf(userCharInput)==-1) //getLetters is the StringBuilder, and the userCharInput is a String.
{
playerCounter++;
}
This is the section that I seem to have trouble in, I’ve looked at different indexOf examples and I’ve formulated this to work with my program.
The problem is, It doesn’t work. I set it so the player has 3 chances to guess the word, since the default word is “apple” I guessed ‘a’, ‘p’, and ‘l’, which leaves ‘e’ to be guessed. Now I intentionally make 3 incorrect guesses and it doesn’t proc the next else if:
else if(playerCounter == 3)
{
System.out.println("All lives are gone! Game Over!");
playerCounter = 1; //resets the playerCounter to one.
System.exit(0);
}
Any help will be greatly appreciated.
The reason it was not working was because of the
indexOfmethod being used improperly,it was partially because of the ordering of the if statements, but that was very miniscule to the primary issue. What had to be changed was the way I used theindexOfmethod.ie. instead of
gletter.indexOf(character);it should have beenword.indexOf(character);where
wordwas the word that had to be guessed, andgletterwas theStringBuilderused to keep track of user guesses.