如果猜测的辅音是原始单词的一部分,我正在使用以下代码将猜测的辅音添加到一串星中。最初,我一直wordWithGuess
在调用getCurrentResult
. 但这样做的结果是,新内容被添加到了末尾,并且wordWithGuess
不断变长(而不是仅仅替换最近猜测的字母)。
运行下面的代码时,输出是
猜到r后:*****r****** 猜后s:************ 猜到t后:**tt******** 猜后 l: ********ll** 猜测n后:***********n
我的目标是:
猜到r后:*****r****** 猜到s后:*****r****** 猜到t后:**tt*r****** 猜到l后:**tt*r**ll** 猜测n后:**tt*r**ll*n
示例代码如下:
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());
}
}
}