0

I am trying to build a simple console app game, Hangman! I have a while loop that repeats while the counter is not equal to the maximum number of guesses, however, I would like for the loop to break and end the program when one of the two conditions is met, either counter equals the maximum number of guesses, OR when the users guess the word.

here is some of my code:

char[] Guess_Word = "ab".ToLower().ToArray();
char[] GuessValues = new char[Guess_Word.Length];
//run while loop to display message instructions
while ((Counter != Max_Guess) || (Guess_Word == GuessValues)) 
{

    Console.Write("\n\nEnter a letter: ");

    Letter = Char.ToLower(Convert.ToChar(Console.ReadLine()));

    //testing to see if the letter is in word
    if (Guess_Word.Contains(Letter))
    {
        Console.WriteLine("You've guessed correctly!");

        for (var i = 0; i < Guess_Word.Length; i++)
        {
            if (Letter == Guess_Word[i])
            {
                GuessValues[i] = Guess_Word[i];                                
            }                
        }

        Correct_Guess++;
        Console.WriteLine(GuessValues);
    }
    else
    {
        Console.WriteLine("You've guessed incorrectly!");
        Console.WriteLine(GuessValues);
        Incorrect_Guess++;
    } 

    Counter++;
}

The second conditional statement in the while loop is always false, even when the indexes have the same values.

Camilo Terevinto
  • 31,141
  • 6
  • 88
  • 120
  • You could also convert them to strings like this `var guessWordString = new string(Guess_Word)` and use `==` to compare the two strings. Be aware strings are immutable so you must construct a new one every time the char array changes. – Zer0 Jun 27 '18 at 01:03

1 Answers1

2

You should modify the while statement to reflect the desired conditions. According to the explanation, you want the loop to break either if the maximum count is reached or if the user guessed correctly. That is: "run the loop while the count is not exceeded AND the guessed answer is not the correct one". It would be something like this:

while ((Counter <= Max_Guess) && (Guess_Word != GuessValues)) 
        { ... }

The loop will end automatically when one of these conditions is no longer met.

Joel Coehoorn
  • 399,467
  • 113
  • 570
  • 794
Omar
  • 1,005
  • 11
  • 11