1

I am working on a "guess the secret word" game in Java. I have a char array containing _'s relative to the amount of letters in the secret word. I am writing a method that will replace the _'s with the guessed letter. My problem is when I have multiple of the same letters; only the first occurrence is replaced. This is my code:

public void replaceBlank(char letter){
    if(guessLetter(letter)==true){
        int x=getSecretWord().indexOf(letter);
            charArray[x]=letter;
        }
   }

The code inside the if is the piece that deals directly with replacing the _'s. I'm thinking that I need a for loop, but I'm not sure how to implement it.

2
  • Side note: if(guessLetter(letter)) is enough Commented Mar 8, 2015 at 21:07
  • You have to loop through the whole array Commented Mar 8, 2015 at 21:08

2 Answers 2

1

indexOf returns only the index of the first occurrence of a character. Instead of using it, I'd treat the secret word as an array and just iterate over it:

public void replaceBlank(char letter) {
    char[] secret = getSecretWord().toCharArray();
    for (int i = 0; i < secret.length; ++i) {
        if (secret[i] == letter) {
            charArray[i] = letter;
        }
    }
}
Sign up to request clarification or add additional context in comments.

3 Comments

I don't think getSecretWord() returns a char[].
@m0skit0 arg, was missing a call to toCharArray() there - fixed. Thanks!
Or you can keep secret as a String and use secret.charAt(i) to access the characters. That will save copying the characters out of the string to create the char array.
0

You have to loop through the whole array, for each index check if it's the letter, then replace.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.