Reputation: 83
I am making a Hangman game. I've almost finished it, but the code I've written, whenever there's two spots or more to be replaced in the hidden word with the guessed letters, works only for the first one. For example, if the word to be found is "ball", and the user enters "b", and "l", instead of "b_ll", the word that he'll get back as the hidden word is "b_l_". This is kind of a weird exercise, since the user first types the letters, without getting feedback after each guess. Here's the code.
for (int c = 0; c < guessedLetters.length(); c++)
{
if (wordToBeFound.contains(Character.toString(guessedLetters.charAt(c))))
{
hiddenWordChars[wordToBeFound.indexOf(guessedLetters.charAt(c))] =
guessedLetters.charAt(c);
}
}
Thank you in advance.
Upvotes: 1
Views: 114
Reputation: 643
The problem is that indexOf() provides only the first index it finds. Meaning that the code above stops after the first hit. A solution would be:
for (int c = 0; c < guessedLetters.toCharArray().length(); c++)
{ // for each guessed letter
for(int c1 =0; c1<wordToBeFound.toCharArray().length; c1++){ //look at each letter in the word, searching for a match
if(guessedLetters[c]==hiddenWordChars[c1]){
hiddenWordChars[c1] = guessedLetters[c];
}
}
}
Upvotes: 2