Java Switch and Or

Possible duplicate:
Can I use OR statements in Java switches?

I have a switch statement. Is there a way to do or operator in the switch. Those.

switch(val){

case 1
//Do Stuff
break;

case 2
//Do Stuff
break;

case 3
//Do Stuff
break
}

Instead, do something like

switch(val){

case 1 or 3
//Do Stuff
break;

case 2
//Do Stuff
break;

}
+3
source share
4 answers

Yes, try the following:

switch(val){

    case 1: case 3:
        //Do Stuff
        break;

    case 2:
        //Do Stuff
        break;

    default:
        //Do Stuff
        break;

}

Remember to also include the default case.

+9
source
switch(val) {

case 1:
case 3:
  //Do Stuff
  break;

case 2
  //Do Stuff
  break;
}
+2
source

Yes:

switch(val){
    case 1:
    case 2:
       //Do Stuff
       break;
    case 3:
       //Do Stuff
       break;
    default:
       break;
}
0
source
switch(val) {

case 1:    
case 2:
   //Do Stuff
   break;       
case 3:
   //Do Stuff
   break;
}
0
source

All Articles