Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiple values in switch case / converting ifs to switch statement

I have a big list of Ifs, and I want to change it into a switch statement. Currently it looks like this:

if(x == 1){
    ...
}
if(x == 2){
    ...
}
if(myArray.contains(x)){
    ...
}

In actuality it's a bit longer than this, but it's the third if in the example that confuses me - how do I change that around to get it to work in a switch, or is it even possible?

like image 617
Steve Avatar asked Jul 01 '26 19:07

Steve


2 Answers

You could do something like this, but YMMV according to possible exit conditions in your code:

switch (x) {
case 1: 
  ...
  break;
case 2:
  ...
  break;
case 3:
case 4:
  ... multi-case
  break;
default:
  if(myArray.contains(x)){
    ...
  }
}
like image 63
solendil Avatar answered Jul 03 '26 07:07

solendil


Switch statement can be used only to test equality of x

So if not equality conditions like (if(myArray.contains(x))) must come at the end, then you can copy paste this into default section of switch

It would look this way

    switch (x) {
     case 1:   ...; break;
     case 2:   ...; break;
     default: if(myArray.contains(x)) ...
    }

If not equality conditions would need to be in the middle, then its not possible to use switch.

reference: http://docs.oracle.com/javase/tutorial/java/nutsandbolts/switch.html

like image 37
dnsmkl Avatar answered Jul 03 '26 09:07

dnsmkl



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!