How to use greater than or equal in a switch statement

后端 未结 8 2404
忘掉有多难
忘掉有多难 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;
    }
    

提交回复
热议问题