I'm using the following code to add a guessed consonant to a string of stars if the guessed consonant is part of the original word. Initially I was keeping wordWithGuess
between calls to getCurrentResult
. But the result of this was that the new content was added to the end, and wordWithGuess
kept getting longer (instead of just replacing the most recently guessed letter).
When running the code below, the output is
After guessing r: *****r****** After guessing s: ************ After guessing t: **tt******** After guessing l: ********ll** After guessing n: ***********n
My goal is for it to be:
After guessing r: *****r****** After guessing s: *****r****** After guessing t: **tt*r****** After guessing l: **tt*r**ll** After guessing n: **tt*r**ll*n
Sample code follows:
public class Sample {
String targetWord;
String wordWithGuess = "";
public Sample(String targetWord) {
this.targetWord = targetWord;
}
public void guess(String consonant) {
wordWithGuess = "";
for (int i = 0; i < targetWord.length(); i++) {
if (targetWord.substring(i, i + 1).equals(" ")) {
wordWithGuess += " ";
} else if (targetWord.substring(i, i + 1).equals(consonant)) {
wordWithGuess += consonant;
} else {
wordWithGuess += "*";
}
}
}
public String getCurrentResult() {
return wordWithGuess;
}
public static void main(String args[]) {
String targetWord = "bitterbollen";
Sample sample = new Sample(targetWord);
String[] guesses = { "r", "s", "t", "l", "n" };
for (String guess : guesses) {
sample.guess(guess);
System.out.println("After guessing " + guess + ": "
+ sample.getCurrentResult());
}
}
}