java - switch statement with range of int

最后都变了- 提交于 2019-12-05 05:24:42

On the JVM level switch statement is fundamentally different from if statements.

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

In Java switch statement does not support ranges. You have to specify all the values (you might take advantage of falling through the cases) and default case. Anything else has to be handled by if statements.

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

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.

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
}
MC Emperor

If you really want to use switch statements—here is a way to create pseudo-ranges with enums, so you can switch over the 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 getFrom(int score) {
        return Arrays.asList(Range.values()).stream()
            .filter(t -> (score >= t.minValue && score <= t.maxValue))
            .findAny()
            .orElse(OTHER);
    }
}

And then your switch:

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

    case TWO_HUNDRED:
        // Do something
        break;

    case SIXTEEN_HUNDRED:
        // Do another thing
        break;

    case OTHER:
    default:
        // Do a whole different thing
        break;
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!