我使用下面的代碼來添加一個猜測的輔音到一串恆星,如果猜測的輔音是原始單詞的一部分。最初,我在撥打getCurrentResult
的電話之間保留wordWithGuess
。但結果是新內容被添加到最後,並且wordWithGuess
不斷變長(而不是僅僅取代最近猜到的字母)。猜測方法(非常基本的java)
當運行下面的代碼,輸出是
After guessing r: *****r****** After guessing s: ************ After guessing t: **tt******** After guessing l: ********ll** After guessing n: ***********n
我的目標是爲它是:
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
示例代碼如下:
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());
}
}
}
爲什麼我會陷入低谷,我做錯了什麼? – Jente
爲了更快提供更好的幫助,請發佈[SSCCE](http://sscce.org/)。 –
有人曾將此鏈接與我聯繫過,但我不太明白。你可能會聯繫我一個例子嗎?謝謝 – Jente