Replacing the parts of a string with a given index position of the actual string Java -
i'm little short handed on understanding how can proceed code. i'm doing hang-man game , made copy of the actual word. copy replaced blank spaces , i'm wondering how can replace blank spaces when player correctly guesses word
while(!gameover && difficulty.equals("1") || difficulty.equals("3") || difficulty.equals("2")){ system.out.println(userword); system.out.print("enter guess! make sure it's 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 here system.out.println("you guessed wrong letter! keep guessing!"); break; } else{ system.out.println("you've guessed right letter!"); string jake = word.indexof(choice); userword = userword.replace(userword,jake); break; and game loop. in else statement @ bottom don't know how i'm suppose work out. @ bottom can index position of player's guess in actual word.
strings immutable in java. you'll want construct new string.
one way this:
char characterguessed = choice.charat(0); stringbuilder builder = new stringbuilder(); for(int = 0; < word.length(); i++) { if(word.charat(i) == characterguessed) { builder.append(characterguessed); } else { builder.append(userword.charat(i)); } } userword = builder.tostring();
Comments
Post a Comment