Evan Vukasinovic Evan Vukasinovic - 6 months ago 5
Java Question

JAVA - Hangman game that keeps the correct letter entered in the unknown letters

if(letterGuessBoolean == true) {
System.out.println("Nice job! That was correct!");
for (position = 0; position < pickRandomWord.length(); position++) {
if (pickRandomWord.charAt(position) == letterGuess) {
System.out.print(letterGuess);
}
else {
System.out.print(unknownLetters);
}
}
}


loop does save the word properly, the unknown character never save the correct way.

Answer

You are printing out the latestly guessed letter only, because this is the only thing you are checking:

pickRandomWord.charAt(position) == letterGuess

You need to remember somehow and somewhere, which letters have been guessed previously. One variant could be the following:

String pickRandomWord = ""; // select your random word
char[] displayOutput = new char[pickRandomWord.length()];
for(int n = 0; n < displayOutput.length; ++n)
    displayOutput[n] = '-';

/* ... */

if(letterGuessBoolean) // do not compare against true, if it is already boolean!
{
    for(int position = 0; position < pickRandomWord.length(); ++position)
    {
        if (pickRandomWord.charAt(position) == letterGuess)
        {
            displayOutput[position] = letterGuess;
        }
        System.out.print(displayOutput[position]);
    }
}
Comments