So I have been learning Java for a little over a month now, and I have a hang man game that I am making but I am having trouble with replacing characters in my string. I have it written so you have two strings, one is called "word" which contains the word to be guessed and the other is called "clone" which is a clone of the word that replaces all the characters with underscores. Then as you guess a letter it checks the string "word" to make sure it contains it, and if it does it replaces the underscore in "clone" with that letter.
while (this.guessesLeft >= 0) {
char letter;
int letterIndex;
getGuess();
if(this.word.contains(this.letterGuessed)) {
StringBuilder newString = new StringBuilder(this.clone);
letterIndex = this.word.indexOf(this.letterGuessed);
letter = this.word.charAt(letterIndex);
newString.setCharAt(letterIndex, letter);
this.clone = newString.toString();
} else {
this.guessesLeft--;
}
printGameBoard();
}
The problem that I'm having is that if you guess a letter and the string contains two of a character it only shows one. For example, here is my output if the word "burrito" is used.
Guess a letter: r
bur____
You have 5 guess left before you die!
Guess a letter: i
bur_i__
You have 5 guess left before you die!
Guess a letter: r
bur_i__
You have 5 guess left before you die!
How would I edit my game logic so that it if the letter "r" is guessed it puts both R's in the string and not just one? Thanks in advance for the help!
indexOf(int ch). There is also a version that accepts the index where to start the search,indexOf(int ch, int fromIndex). You will need to loop that until you come to the end of the string, or there are no more instances of the character (returned index is-1).StringBuilderor worry about the immutability ofString(String.toCharArray()would be the easy way to get it).