If with 3 conditions and at least 2 true?

Asked

Viewed 1,524 times

3

Suppose I have the following if

if(a || b || c == true)

In this case, just one of the values is true to activate the condition, but I would like the condition to activate only when at least 2 of the past values are true, is it possible? If yes, how?

3 answers

5

Gambiarra based on type Juggling:

if(a + b + c >= 2) {

}

Explanation: with the addition operator, the boolean values will be converted into numbers, with true availing 1 and false availing 0. If the sum result is 2 or more, it means that you have at least 2 true. This works as long as your variables are Boolean type, or Number type with values 0 or 1. If necessary, convert them before the if.

3

I don’t know if there’s a way "automatic" to control it, but you can group the conditions:

if ((a && b) || (a && c) || (b && c))

1

To use two conditions, you must use && instead of ||

|| means OR

&& means AND

if (a && b || c)


If A and B is true or C

I mean, C if it’s real, it’s gone. It’s gone.

  • 1

    If I have understood correctly, the question demands that two of the conditions be true; in this answer, if A and B are false and C true, he enters the if. Or did I misunderstand? P

  • If A and B are true at the same time, OR the C is true, enter the IF. That is, if O is true, B is false and C is true, it will enter by the rule of C. .

Browser other questions tagged

You are not signed in. Login or sign up in order to post.