How many conditions can I add in a while loop?

0

I start in the programming and I come to your help.

I made a while loop which responds correctly when I add a condition, however when I add a 2nd condition the loop goes into an infinite cycle even though the conditions are true and must come out of the loop. loop.

I share my code and I am grateful with your quick answers:

var operacion= prompt("Ingresu su operación");
while(operacion!="sumar" || operacion!="restar"){           
    operacion= prompt("Esta operación no está contemplada");    
}
    
asked by Rank16 25.07.2017 в 18:12
source

2 answers

1

The problem is the type of condition you are using. || or also known as OR check if one of the two conditions is true or not.

So if we analyze what your code does:

while (operacion != "sumar" || operacion != "restar")

  • Check that the variable operacion that you received as text from the prompt is different from either "subtract" or "add".
  • If the user enters "subtract" then check both conditions:
  • operacion != "sumar" - > it is fulfilled, it no longer reviews the other condition, so it continues within the cycle.
  • If the user enters "add" then check both conditions:
    • operacion != "sumar" is not met, check the following condition, operacion != "restar" , it is fulfilled so it continues within the cycle.

As you can see both conditions will never be fulfilled, because that is part of the condition || or one or the other but not both. If I understand what you want to do you must change your condition to a AND also known as &&

var operacion= prompt("Ingresu su operación");

while(operacion!="sumar" && operacion != "restar"){
    operacion= prompt("Esta operación no está contemplada"); 
}
    
answered by 25.07.2017 / 18:26
source
0

This loop will always be true because you are saying that "operation" is different from "add" or different from "subtract", you have to change the OR "||" for an AND "& amp;"

    
answered by 25.07.2017 в 18:22