0

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!

2
  • 2
    If you were to step through your code in your debugger with a simple example you would be able to see what the problem is yourself. Commented Jan 14, 2016 at 13:19
  • Thank you, i'll take a look in the debugger to see what I can find. :) Commented Jan 14, 2016 at 13:26

1 Answer 1

3

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 Strings are immutable). You must assign the new String returned by this method back to replacementString :

replacementString = replacementString.replace(replacementString.charAt(i), inputAnswerChar)
Sign up to request clarification or add additional context in comments.

3 Comments

Thank you for the quick reply first of all :) Do you maybe have any idea of how I could re-write it? In steps, this is what i need it to do: -if inputAnswer contains guessInputString letter -for each character -if inputAnswer letter equals guessInputString letter -replace replacementString letter with inputAnswer letter
@bakfietsland it's hard to say without seeing more of your code. You have 3 Strings. How are they initialized? Should they all have the same length?
These 3 strings are initialized as follows: -inputAnswer is retrieved by a br.readLine(); -guessInputString is later retrieved by a br.readLine(); -replacementString is a string that is made up of '_' characters for each letter of inputAnswer

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.