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?
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)){
...
}
}
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
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