How to use greater than or equal in a switch statement

后端 未结 8 2466
忘掉有多难
忘掉有多难 2021-02-19 04:10

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;

i         


        
相关标签:
8条回答
  • 2021-02-19 04:44

    A switch statement is for running code when specific values are returned, the if then else allows you to select a range of values in one statement. I would recommend doing something like the following (though I personnally prefer the Integer.signum method) should you want to look at multiple ranges:

    int i;
    
    if (var1 > var2) {
      i = 1;
    }
    else if (var1 == var2) {
      i = 0;
    }
    else {
      i = -1;
    }
    
    0 讨论(0)
  • 2021-02-19 04:45

    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;
    }
    
    0 讨论(0)
  • 2021-02-19 04:45

    You're better off with the if statements; the switch approach is much less clear, and in this case, your switch approach is objectively wrong. The contract for Comparable#compareTo does not require returning -1 or 1, just that the value of the returned int be negative or positive. It's entirely legitimate for compareTo to return -42, and your switch statement would drop the result.

    0 讨论(0)
  • 2021-02-19 04:52

    Unfortunately you cannot do that in java. It's possible in CoffeeScript or other languages.

    I would recommend to use an if-else-statement by moving your "do stuff" in extra methods. In that way you can keep your if-else in a clearly readable code.

    0 讨论(0)
  • 2021-02-19 04:53

    Java only supports direct values, not ranges in case statements, so if you must use a switch, mapping to options first, then switching on that, as in the example you provide is your only choice. However that is quite excessive - just use the if statements.

    0 讨论(0)
  • 2021-02-19 04:58

    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.

    0 讨论(0)
提交回复
热议问题