What is the best way to check if variable is bigger than some number using switch statement? Or you reccomend to use if-else? I found such an example:
int i; if(var1>var2) i = 1; if(var1=var2 i = 0; if(var1<var2) i = -1; switch (i); { case -1: do stuff; break; case 0: do stuff; break; case 1: do stuff; break; }
What can you tell a novice about using "greater than or equal" in switch statements?
SWITCH versus IFS However, SWITCH is limited to exact matching. It is not possible to use operators like greater than (>) or less than (<) with the standard syntax.
The switch statement compares the String object in its expression with the expressions associated with each case label as if it were using the String. equals method; consequently, the comparison of String objects in switch statements is case sensitive.
The switch statement uses the strict comparison ( === ). Third, execute the statement in the case branch where the result of the expression equals the value that follows the case keyword. The break statement exits the switch statement.
You can't use “||” in case names.
Not sure if this is what you're asking, but you could do it this way:
int var1; int var2; int signum = Long.signum((long)var1 - var2); switch(signum) { case -1: break; case 0: break; case 1: break; }
I would strongly recommend a if(var1>var2){}else if (var1==var2) {} else {}
construct. Using a switch here will hide the intent. And what if a break
is removed by error?
Switch is useful and clear for enumerated values, not for comparisons.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With