10

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.

WXR
  • 481
  • 1
  • 7
  • 18

4 Answers4

13

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.

Crazyjavahacking
  • 9,343
  • 2
  • 31
  • 40
8

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 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;
}
MC Emperor
  • 22,334
  • 15
  • 80
  • 130
7

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
}
akash
  • 22,664
  • 11
  • 59
  • 87
6

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.

Matter Cat
  • 1,538
  • 1
  • 14
  • 23