I'm trying to make a hangman game. s is the string that contains the user's guess, and hiddenWord is a string of all question marks until the user guesses one of the letters correctly. How could I replace the question marks with the s string?
public void correctGuess()
{
hiddenWord.replace ("?", s);
JOptionPane.showMessageDialog (null, "That was correct! Guess again.");
}
The replace
method doesn't change the original String
, which is immutable. It returns the modified String
. Try
hiddenWord = hiddenWord.replace("?", s);
You can't simply replace characters in strings in java, as strings are immutable. What you can do is create a new string the way rgettman suggested.
But would it not replace all the question marks in the hiddenWord with the s instead of replacing them only at the index(s) where the letter, which the user correctly guessed, is found in the hiddenWord?
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.