I'm just a little short handed on understanding how I can proceed with my code. I'm basically doing a hang-man game and I made a copy of the the actual word. The copy is replaced with blank spaces and I'm wondering how I can replace the blank spaces when the player correctly guesses a word
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;
and this is my game loop. in the else statement at the bottom I don't know how I'm suppose to work this out. At the bottom I can get the index position of the player's guess in the actual word.
答案 0 :(得分:0)
字符串在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();