java - switch statement with range of int

2019-04-26 15:59发布

问题:

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

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

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

回答1:

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.



回答2:

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.



回答3:

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
}


回答4:

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