Avoid Switch statement redundancy when multiple Cases do the same thing?

本秂侑毒 提交于 2020-01-01 04:51:06

问题


I have multiple cases in a switch that do the same thing, like so: (this is written in Java)

 case 1:
     aMethod();
     break;
 case 2:
     aMethod();
     break;
 case 3:
     aMethod();
     break;
 case 4:
     anotherMethod();
     break;

Is there any way I can combine cases 1, 2 and 3 into one case, since they all call the same method?


回答1:


case 1:
case 2:
case 3:
    aMethod();
    break;
case 4:
    anotherMethod();
    break;

This works because when it happens to be case 1 (for instance), it falls through to case 2 (no break statement), which then falls through to case 3.




回答2:


Sure, you can allow case clause sections for 1 & 2 to 'fall through' to clause 3 and then break out of the switch statement after that:

case 1:
case 2:
case 3:
     aMethod();
     break;
case 4:
     anotherMethod();
     break;



回答3:


Below is the best you can do

case 1:
case 2:
case 3:
     aMethod();
     break;
 case 4:
     anotherMethod();
     break;



回答4:


It's called the "fall through" pattern:

case 1:  // fall through
case 2:  // fall through
case 3: 
   aMethod(); 
   break; 
case 4: 
   anotherMethod(); 
   break; 


来源:https://stackoverflow.com/questions/12965738/avoid-switch-statement-redundancy-when-multiple-cases-do-the-same-thing

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!