ste*_*ade 18 java switch-statement
在Java中,我是否只能通过switch声明中的一个案例?我明白,如果我break,我会落到switch声明的最后.
这就是我的意思.鉴于以下代码,在案例2中,我想执行案例2和案例1.在案例3中,我想执行案例3和案例1,但不是案例2.
switch(option) {
case 3: // code
// skip the next case, not break
case 2: // code
case 1: // code
}
Run Code Online (Sandbox Code Playgroud)
m0s*_*it0 10
将代码放入方法并根据需要调用.按照你的例子:
void case1() {
// Whatever case 1 does
}
void case2() {
// Whatever case 2 does
}
void case3() {
// Whatever case 3 does
}
switch(option) {
case 3:
case3();
case1();
break;
case 2:
case2();
case1();
break;
case 1:
case1(); // You didn't specify what to do for case 1, so I assume you want case1()
break;
default:
// Always a good idea to have a default, just in case demons are summoned
}
Run Code Online (Sandbox Code Playgroud)
当然case3(),case2()...是非常糟糕的方法名称,你应该重命名为更有意义的方法实际上做什么.
mil*_*ose 10
我的建议是除了以下情况之外的任何事情都不要使用fallthrough :
switch (option) {
case 3:
doSomething();
break;
case 2:
case 1:
doSomeOtherThing();
break;
case 0:
// do nothing
break;
}
Run Code Online (Sandbox Code Playgroud)
也就是说,给几个案例提供完全相同的代码块来处理它们(通过"堆叠" case标签),使得这里的流程或多或少变得明显.我怀疑大多数程序员直观地检查案例是否通过(因为缩进使案例看起来像一个正确的块)或者可以有效地读取依赖它的代码 - 我知道我没有.