thank you in advance for reading about my problem.
I am making a Hangman game where I want to print out a hidden version of the current word, but I would like to update it when a correct letter is guessed (on the right spot, too). I've been looking around StackOverflow but I just can't seem to find an explaination that I understand. If someone could help me, that would be great. :D
I'll post the for-loop that this is about. I can post more of the code if you might need it. The answerInput and guessInputString are both read from the console earlier in my code using a br.readLine() method.
for (int i = 0; i < inputAnswer.length(); i++) {
char inputAnswerChar = inputAnswer.charAt(i);
char guessInputChar =guessInputString.charAt(i);
if (inputAnswerChar == guessInputChar) {
replacementString.replace(replacementString.charAt(i), inputAnswerChar);
}
}
Thank you for any help that you can give me!
Your code is assuming that guessInputString
and replacementString
both have at least as many characters as inputAnswer
, which is obviously wrong to assume, since your loop only guarantees that the i
'th character exists for the inputAnswer
String.
BTW, replacementString.replace(replacementString.charAt(i), inputAnswerChar)
has no effect, since it cannot change the String
it is executed for (since String
s are immutable). You must assign the new String
returned by this method back to replacementString
:
replacementString = replacementString.replace(replacementString.charAt(i), inputAnswerChar)
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.