次のコードを使用して、推測された子音が元の単語の一部である場合に、推測された子音を星の文字列に追加しています。wordWithGuess
当初、私はへの呼び出しの間を保っていましたgetCurrentResult
。しかし、その結果、新しいコンテンツが最後に追加され、wordWithGuess
長くなり続けました (最近推測された文字を置き換えるだけではありません)。
以下のコードを実行すると、出力は次のようになります。
rを推測した後: ****r******** 推測後: ************ 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());
}
}
}