[英]Java switch case fall through
我有一個Java開關案例,如下所示:
switch(int example)
{
case 1: //Do different
break;
case 2: //Do different
break;
/** For int more than 2, then I need
for it to do something same.
*/
case 3://Do different and case6
break;
case 4://Do different and case6
break;
case 5://Do different and case6
break;
case 6:
break;
}
什么是一種優雅的方式,沒有案例3-5調用特殊情況6功能? (我在這里使用int,但這是一個例子,所以我不能使用if(int >2)
)
一個開關真的不能完全按照你的要求開箱即用。 您可以使用嵌套開關構建類似的東西:
outer_switch: switch (example) {
case 1: System.out.println("1");
break;
case 2: System.out.println("2");
break;
default: {
switch (example) {
case 3: System.out.println("3");
break;
case 4: System.out.println("4");
break;
case 5: System.out.println("5");
break;
case 6: System.out.println("6");
break;
default: break outer_switch;
}
System.out.println("not 1 nor 2");
}
}
注意outer_switch
上標記的中斷,如果example
不滿足任何內部情況,這是繞過共享代碼的一種方法。
我能想到的一種方法是將代碼移動到不同的功能。 像這樣的東西。
void case1(){
// do something
}
...
void case3(){
// do something
case6();
}
...
void case6(){
// do something
}
// This switch is in some other method.
switch(int example)
{
case 1: //Do different
case1();
break;
...
case 3://Do different and case6
case3(); //internally calls case 6
break;
...
case 6:
case6();
break;
}
或者你甚至可以為每個案例使用不同的方法,並在case 3:
調用case3()
和case6()
方法case 3:
。 無論哪種方式,方法解決方案都可以工作,而恕我直言,它會更優雅和多個switch
語句。
我不確定它是否優雅,但有一種方法是擁有兩個switch
塊:
switch(int example)
{
case 1: //Do different
break;
case 2: //Do different
break;
case 3:
// Do whatever
break;
case 4:
// Do whatever
break;
case 5:
// Do whatever
break;
}
switch(int example)
{
case 3:
case 4:
case 5:
case 6:
// Do whatever (case 3-5 fall through)
break;
}
這也可能是您想要實現的目標的解決方案:
switch(example){
case 1:
System.out.println(example);
break;
case 2:
System.out.println(example);
break;
case 3:
System.out.println("I'm case 3");
case 4:
if (example == 4){
System.out.println("I'm case 4");
}
case 5:
if (example == 5){
System.out.println("I'm case 5");
}
case 6:
System.out.println("I'm in extra case " + example);
break;
}
這個想法是你添加一個額外的條件檢查,讓你的代碼落到所有分支,而不執行不必要的分支。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.