因此,我现在学习Java已有一个多月了,我正在制作一个子手游戏,但是在替换字符串中的字符时遇到了麻烦。我写了它,所以有两个字符串,一个叫做“ word”,其中包含要猜测的单词,另一个叫做“ clone”,它是单词的克隆,用下划线替换所有字符。然后,当您猜到一个字母时,它会检查字符串“ word”以确保包含它,如果确实包含,则会用该字母替换“ clone”中的下划线。
while (this.guessesLeft >= 0) {
char letter;
int letterIndex;
getGuess();
if(this.word.contains(this.letterGuessed)) {
StringBuilder newString = new StringBuilder(this.clone);
letterIndex = this.word.indexOf(this.letterGuessed);
letter = this.word.charAt(letterIndex);
newString.setCharAt(letterIndex, letter);
this.clone = newString.toString();
} else {
this.guessesLeft--;
}
printGameBoard();
}
我遇到的问题是,如果您猜一个字母并且该字符串包含两个字符,那么它只会显示一个。例如,如果使用单词“ burrito”,这是我的输出。
Guess a letter: r
bur____
You have 5 guess left before you die!
Guess a letter: i
bur_i__
You have 5 guess left before you die!
Guess a letter: r
bur_i__
You have 5 guess left before you die!
我如何编辑我的游戏逻辑,以便在猜出字母“ r”时将两个R都放在字符串中而不是一个字符串中?先谢谢您的帮助!
最佳答案
您需要查找字母的所有索引,然后全部替换。
目前,您只寻找第一个。
要查找所有索引,请查找字母的第一个匹配项,然后找到一个(indexOf返回一个正值),请继续使用indexOf(int ch, int fromIndex)方法从最后一个位置开始查找,直到找到所有索引(indexOf返回-1) )。
这是一个例子:
if(this.word.contains(this.letterGuessed)) {
// look for an occurrence,
// if you have one, keep looking for others until you have them all (ie: index = -1)
List<Integer> indexes = new ArrayList<>();
int index = this.word.indexOf(this.letterGuessed);
while (index >= 0) { // <- that will loop until the indexOf returns a -1
indexes.add(index);
index = this.word.indexOf(this.letterGuessed, index+1);
}
// replace at all the found indexes
StringBuilder newString = new StringBuilder(this.clone);
for(int letterIndex : indexes) {
char c = this.word.charAt(letterIndex);
newString.setCharAt(letterIndex, c);
}
this.clone = newString.toString();
} else {
this.guessesLeft--;
}
您也可以一次完成此操作,而无需将索引保存在列表中:
if(this.word.contains(this.letterGuessed)) {
StringBuilder newString = new StringBuilder(this.clone);
int index = this.word.indexOf(this.letterGuessed);
while (index >= 0) {
char c = this.word.charAt(index);
newString.setCharAt(index, c);
index = this.word.indexOf(this.letterGuessed, index+1);
}
this.clone = newString.toString();
System.out.println("clone = " + clone);
} else {
this.guessesLeft--;
}