user2596655
user2596655

Reputation: 9

If statement not working as intended

I have a bit of code here and what I want to happen is that every time it is triggered the integer 'lives' goes down by one. Here is my code.

  if (match == NO)

    {
        self.wrongLetters = [self.wrongLetters stringByReplacingOccurrencesOfString:letterToCheck withString:@""];
        self.wrongLetters = [self.wrongLetters stringByAppendingString:letterToCheck];

        while (!lives == 0)
        {
            lives--;
            self.HangmanStatus.text = [[NSString alloc] initWithFormat:@"Lives Left: %d", lives ];
        }
    }

But instead of going down by one it goes down all the way to 0. Am I triggering it incorrectly? Advice would be awesome, Thanks

Upvotes: 0

Views: 77

Answers (3)

rmaddy
rmaddy

Reputation: 318924

You want:

while (lives != 0) {
}

Another option would be:

while (lives > 0) {
}

This will guard against lives being negative somehow.

But if you just want lives to go down once, change the while to if.

if (lives > 0) {
}

The expression !lives == 0 negates the value of lives then checks to see if that value is equal to 0. Not what you want.

Upvotes: 2

Ben Pious
Ben Pious

Reputation: 4805

Lives is inside of a while loop with the condition "while lives is not equal to 0, decrement lives." Therefore, the statements in the condition are run until the condition is satisfied -- until lives is equal to zero.

Upvotes: 0

MikeS
MikeS

Reputation: 3921

while(!(lives == 0)) should fix your issue.

Or, better yet, while(lives != 0)

Because of the order in which operations are applied, while(!lives == 0) is actually applying the ! operator to lives, which is not what you want to do.

Upvotes: 1

Related Questions