Home > Blockchain >  I've made an infinite loop and can't seem to figure out what I did wrong
I've made an infinite loop and can't seem to figure out what I did wrong

Time:09-21

I'm writing a program for a simple game of Odds and Evens, but I can't seem to figure out what's wrong with my while loop.

It's meant to make it so that while the user doesn't enter either odds, Odds, evens, or Evens an alert comes up saying 'Please enter either odds or evens'.

But, whenever I run the code, it just turns into an infinite loop, repeating the alert, no matter what I put in. Even if it is the correct response I want.

var oddEven = prompt('Would you like to be odds or evens?', 'Odds') 
while (oddEven != 'odds' || oddEven != 'Odds' || oddEven != 'evens' || oddEven != 'Evens') {
    oddEven = prompt('Please enter either odds or evens');

}

I am very new to programming and just started learning a couple months ago so any advice would be appreciated.

Thanks for the help :)

CodePudding user response:

So it's an Or, any condition that satisfies even one, will evaluate to true. So if I enter 'boo', oddEven != 'boo', and therefore the rest evaluates as true. A better way would be

while (oddEven in ['odds', 'Odds' ...]): 
    oddEven = prompt('Please enter either odds or evens')

CodePudding user response:

Imagine a user gives the input "Odds", what happens in your if statement?

oddEven != 'odds' is false, but we still need to check the others! We need to check the others because you have written || which means "or" - javascript will keep going through each statement until one of them is true.

oddEven != 'Odds' is true. Because it is true, your while-loop immediately continues, again because you have used || - if ANY of the statements is true the code will stop checking statements and continue the loop.

There are lots of ways to fix this but I think the following is best for comparing to how you got stuck:

var oddEven = prompt('Would you like to be odds or evens?', 'Odds') 
while (
    !(oddEven == 'odds' || oddEven == 'Odds' || oddEven == 'evens' || oddEven == 'Evens')
) {
    oddEven = prompt('Please enter either odds or evens');
}

Now in our example, oddEven == 'Odds' is true, but because the whole section is negated by the bang ! at the start, we're taking the opposite of that, so false.

A tidier way of doing this could be as follows:

var oddEven = prompt('Would you like to be odds or evens?', 'Odds') 
while (!['odds', 'Odds', 'evens', 'Evens'].includes(oddEven)) {
    oddEven = prompt('Please enter either odds or evens');
}

This says "while this list of inputs does not include oddEven".

  • Related