Roy Henriquez
Roy Henriquez

Reputation: 81

Hangman while loop not working with ||

I have the following while-loop for a game of Hangman I'm working on:

while(amountOfGuessesLeft > 0 || !wordComplete){
        System.out.println("The word now looks like this: " + filteredWord);
        System.out.println("You have " + amountOfGuessesLeft + " guesses left");
        System.out.print("Your guess: ");
        try {
            guess = br.readLine();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        if(guess.length() == 0 || guess.length() > 1){
            System.out.println("Please just type one letter. Try again.");
        }else if(wordSelected.contains(guess) || wordSelected.contains(guess.toUpperCase())){
            System.out.println("That guess is correct.");
            filteredWord = showGuess(filteredWord, wordLetters,  guess.toUpperCase().charAt(0));
            if(!filteredWord.contains("_")){
                wordComplete = true;
            }
        }else{
            System.out.println("There are no " + guess.toUpperCase() + "'s in this word.");
            amountOfGuessesLeft--;
        }
    }

When the while-loop condition is just amountOfGuessesLeft > 0, everything works fine. However, when I add || !wordComplete, neither condition is applied and the loop never ends. It doesn't throw any errors either. Any help would be appreciated.

Upvotes: 0

Views: 50

Answers (1)

SapuSeven
SapuSeven

Reputation: 1573

You need to use &&.

You want to run the loop as long as there are any guesses left and the user hasn't found the word yet.

Currently, if you run out of guesses and still haven't found the word, !wordComplete will evaluate to true and allows the loop to be executed again.

Upvotes: 3

Related Questions