I need to implement switch case statement with dynamic value for case as below.
int v1 = 5;
int key = xx.getKey();
switch (v1) {
case key:
.......
case key+1:
.......
case key+2:
.......
default:
.......
}
When using this, java complains "case expressions must be constant expressions". Is there a way to use dynamic values in case. (switch variable is also dynamic value)
You cannot have non-constant expressions as cases in your switch statement. However, you can make the cases constant by subtracting key from v1:
switch (v1 - key) {
case 0:
.......
case 1:
.......
case 2:
.......
default:
.......
}
However, this only works because you have simple cases. As @BorisTheSpider points out, in the more general case, you'd need to use if...else statements.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With