java - 具有 int 范围的 switch 语句

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/28892969/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 06:59:40  来源:igfitidea点击:

java - switch statement with range of int

javaif-statementintegerswitch-statementrange

提问by WXR

I want to use a switch statement to check a range of numbers I have found a few places saying something like case 1...5or case (score >= 120) && (score <=125)would work but I just somehow keep on getting errors.

我想使用 switch 语句来检查一系列数字,我发现一些地方说类似 case 1...5case (score >= 120) && (score <=125)可行,但我只是不知何故不断出错。

What I want is if the number is between 1600-1699 then do something.

我想要的是如果数字在 1600-1699 之间,那么做一些事情。

I can do if statements but figured it's time to start using switch if possible.

我可以做 if 语句,但认为是时候开始使用 switch 了。

回答by Matter Cat

As far as I know, ranges aren't possible for switch cases in Java. You can do something like

据我所知,Java 中的 switch case 不可能有范围。你可以做类似的事情

switch (num) {
  case 1: case 2: case 3:
    //stuff
    break;
  case 4: case 5: case 6: 
    //more stuff
    break;
  default:
}

But at that point, you might as well stick with the if statement.

但在这一点上,您不妨坚持使用 if 语句。

回答by CoderCroc

You can use ternary operator, ? :

您可以使用三元运算符, ? :

int num = (score >= 120) && (score <=125) ? 1 : -1;
num = (score >= 1600) && (score <=1699 ) ? 2 : num;
switch (num) {
    case 1 :
       break;
    case 2 :
       break;
    default :
      //for -1
}

回答by Crazyjavahacking

On the JVM level switchstatement is fundamentally different from if statements.

在 JVM 级别上的switch语句与 if 语句根本不同。

Switch is about compile time constants that have to be all specified at compile time, so that javac compiler produces efficient bytecode.

Switch 是关于必须在编译时全部指定的编译时常量,以便 javac 编译器生成高效的字节码。

In Java switchstatement does not support ranges.You have to specify all the values (you might take advantage of falling through the cases) and defaultcase. Anything else has to be handled by ifstatements.

在 Javaswitch语句中不支持范围。您必须指定所有值(您可能会利用案例)和default案例。其他任何事情都必须由if语句处理。

回答by MC Emperor

If you reallywant to use switch statements—here is a way to create pseudo-ranges with enums, so you can switch over the enums.

如果你真的想使用 switch 语句——这里有一种用enums创建伪范围的方法,这样你就可以切换枚举。

First, we'll need to create the ranges:

首先,我们需要创建范围:

public enum Range {

    TWO_HUNDRED(200, 299),
    SIXTEEN_HUNDRED(1600, 1699),
    OTHER(0, -1); // This range can never exist, but it is necessary
                  // in order to prevent a NullPointerException from
                  // being thrown while we switch

    private final int minValue;
    private final int maxValue;

    private Range(int min, int max) {
        this.minValue = min;
        this.maxValue = max;
    }

    public static Range from(int score) {
        return Arrays.stream(Range.values())
            .filter(range -> score >= range.minValue && score <= range.maxValue)
            .findAny()
            .orElse(OTHER);
    }
}

And then your switch:

然后你的开关:

int num = 1630;
switch (Range.from(num)) {

    case TWO_HUNDRED:
        // Do something
        break;

    case SIXTEEN_HUNDRED:
        // Do another thing
        break;

    case OTHER:
    default:
        // Do a whole different thing
        break;
}