Java - switch statement with int range

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

I want the number to be between 1600-1699, then do something.

I can do if, but figured out the time to start using the switch, if possible.

+6
source share
4 answers

At the JVM switch level, the switch significantly different from if statements.

The switch is compile-time constants that must be specified at compile time, so the javac compiler creates efficient bytecode.

Ranges are not supported in the Java switch . . You must specify all values ​​(you can use the failure in cases) and default . Everything else should be handled by if .

+9
source

As far as I know, ranges are not available for switching 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 this point, you can also stick with the if statement.

+5
source

Can you use the 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 } 
+2
source

If you really want to use switch statements, here is a way to create pseudo ranges with enum s, so you can switch enumerations.

First we need to create 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; } 
+1
source

Source: https://habr.com/ru/post/983408/


All Articles