如何在 switch 语句中使用大于或等于

2022-01-19 00:00:00 if-statement switch-statement java

使用 switch 语句检查变量是否大于某个数字的最佳方法是什么?或者您建议使用 if-else?我找到了这样一个例子:

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;

}

关于在 switch 语句中使用大于或等于",你能告诉新手什么?

What can you tell a novice about using "greater than or equal" in switch statements?

推荐答案

不确定这是不是你要的,但你可以这样做:

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;
}

相关文章