Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

My code works for when secretWord contain one \'guess\', but it doesnt work for

ID: 3701353 • Letter: M

Question

My code works for when secretWord contain one 'guess', but it doesnt work for when secretWord contain 2 of the same guess. Example, it work for when guess is 'a', and secretWord is apple, but it doesnt work when guess is 'e', and secretWord is secret......which has 2 'e'

+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

public static String makeGuess(String guess, String secretWord, String disguisedWord) {

String newWord=disguisedWord;

if(secretWord.contains(guess)) {

int id=secretWord.indexOf(guess);

int m = guess.length();

String temp;

StringBuffer buf=new StringBuffer(disguisedWord);

buf.replace(id, id+m, guess);

newWord = new String(buf);

}

return newWord;

}

Explanation / Answer

Error: You are finding only starting index of a guess.

Solution: We need to find all occurences of guess and replace.

Modified Java Function:

public static String makeGuess(String guess, String secretWord, String disguisedWord) {

                String newWord=disguisedWord;

                if(secretWord.contains(guess)) {

                                int id=secretWord.indexOf(guess);

                                while (id >= 0) {

                                                int m = guess.length();

                                                String temp;

                                                StringBuffer buf=new StringBuffer(disguisedWord);

                                                buf.replace(id, id+m, guess);

                                                newWord = new String(buf);

                                                disguisedWord = newWord;

                                                id = secretWord.indexOf(guess, id + 1);

                                }

                }

                return newWord;

}

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote