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;
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.