javaappendcharacter-arrays

Hangman append progress not working properly


My applyGuess method returns the user's progress after each guess, if his guess, in this case is a letter, is inside I append it (+=) to progress, and all the letters soon to be guessed are represented and printed on screen with '*' (stars). For example, the user guessed 'a' and the word has two a's; a***a* (The output) and, for second guess lets choose the letter 'n' if the user guesses 'n', we get; *n**** and not

an**a*

  public String applyGuess(char letterGuessed){
    boolean isLetterInside = hiddenWord.indexOf(letterGuessed) >= 0; 
    char display;
    String progress;

    if (isLetterInside){
        for (char letter: hiddenWord.toCharArray()){
            display = '*';
            if (letter == letterGuessed){
                display = letterGuessed;
                }
            progress += display;
            }
    } else {
        misses++;
        }
    return progress;
}

Thank you!!


Solution

  • What you might be able to do, is keep track of all the guesses that the user has made and build a new prompt on each successive guess.

    private String hiddenWord = "banana";
    private Set<Character> guesses = new HashSet<>();
    private int misses;
    
    
    public String applyGuess(char letterGuessed) {
        if (!guesses.contains(letterGuessed)) {
            guesses.add(letterGuessed);
            if (!hiddenWord.contains(Character.toString(letterGuessed))) {
                misses++;
            }
        }
        char[] progress = hiddenWord.toCharArray();
        for (int index = 0; index < hiddenWord.length(); index++) {
            if (!guesses.contains(hiddenWord.charAt(index))) {
                progress[index] = '*';
            }
        }
        return new String(progress);
    }
    

    What this basically does is checks to see if the user has already used this character or not (I did this so I wouldn't increment the misses count, but you're requirements might be different), adds the char to the list of guesses and then checks to see if the character is in the hiddenWord, if it isn't it increments the misses.

    Because, regardless of what the user does, we need to produce a prompt, the last part of the method creates a char of the hiddenWord and loops over each character in the hiddenWord, where there isn't a matching guess in guesses, it updates the character at that position with a * character.

    It then returns a String representation of the char array.

    Doing something like...

    System.out.println(applyGuess('n'));
    System.out.println(applyGuess('a'));
    System.out.println(applyGuess('b'));
    

    Outputs

    **n*n*
    *anana
    banana
    

    for example