Java 用实际字符串的给定索引位置替换字符串的各个部分
我只是有点缺乏理解如何继续我的代码。我基本上是在做一个吊人游戏,我复制了一个真实的单词。副本被空白替换,我想知道当玩家正确猜一个单词时,我如何替换空白空间。Java 用实际字符串的给定索引位置替换字符串的各个部分,java,Java,我只是有点缺乏理解如何继续我的代码。我基本上是在做一个吊人游戏,我复制了一个真实的单词。副本被空白替换,我想知道当玩家正确猜一个单词时,我如何替换空白空间。 while(!gameOver && difficulty.equals("1") || difficulty.equals("3") || difficulty.equals("2")){ System.out.println(userWord); Syste
while(!gameOver && difficulty.equals("1") || difficulty.equals("3") || difficulty.equals("2")){
System.out.println(userWord);
System.out.print("Enter your guess! Make sure it's a singular letter only!: ");
choice = inputs.nextLine().toLowerCase();
while(choice.length()==1){
int check1 = lettersGuessed.indexOf(choice);
if (check1 == -1){
//System.out.println("b");
lettersGuessed = lettersGuessed+letter;
if (word.indexOf(choice) == -1) {
mistakes++; //mISTAKES - add on to here
System.out.println("You guessed a wrong letter! Keep guessing!");
break;
}
else{
System.out.println("You've guessed a right letter!");
String jake = word.indexOf(choice);
userWord = userWord.replace(userWord,jake);
break;
这是我的游戏循环。在底部的else语句中,我不知道该如何解决这个问题。在底部,我可以得到玩家猜测的实际单词的索引位置。字符串在Java中是不可变的。您需要构造一个新字符串 一种方法是:
char characterGuessed = choice.charAt(0);
StringBuilder builder = new StringBuilder();
for(int i = 0; i < word.length(); i++) {
if(word.charAt(i) == characterGuessed) {
builder.append(characterGuessed);
} else {
builder.append(userWord.charAt(i));
}
}
userWord = builder.toString();
characterGuessed=choice.charAt(0);
StringBuilder=新的StringBuilder();
for(int i=0;i