我在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;
}
一个优雅的方式是什么,sans有一个特殊的情况6函数,情况3-5调用?(我在这里使用int,但这只是一个示例,所以我不能使用if(int >2)
)
发布于 2013-11-23 14:14:26
交换机并不能真正做到您所要求的开箱即用。不过,您可以使用嵌套开关构造类似以下内容的内容:
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
上的标记为break,这是在example
不满足任何内部情况时绕过共享代码的一种方法。
发布于 2013-11-23 14:11:44
我能想到的一种方法是将你的代码移到不同的函数中。就像这样。
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()
方法。无论哪种方式,方法解决方案都会起作用,而且我敢说,它会更优雅,而且会有多个switch
语句。
发布于 2013-11-23 14:13:31
我不确定它是否优雅,但一种方法是拥有两个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;
}
https://stackoverflow.com/questions/20159207
复制相似问题