2011-11-24 32 views
1

我想在java中编写一些代码,可以在交换机中或多次调用同一个案例,使用一些代码,这些代码对于大多数或所有情况都是相同的。现在我必须为每个案例重复一半的代码,因为它被区分大小写的代码包围。在我的脑海中的代码会是这个样子,变化范围为0-3,并打破仅仅意味着停止执行,直到该情况下一个电话,我明白,这可能是除了碰坏如果存在的话,交换机多次调用同一个案例

switch(variable){ 
    case 0: 
    case 1: 
     if(other factors) 
      //add item to next spot in array 
    case 2: 
    case 3://all cases 
     //add items to next 3 spots in array for all cases 
     break; 
    case 0: 
    case 1: 
     if(other factors) 
      //add item to next spot in array 
    case 2: 
    case 3://all cases 
     //add more items to next spot in array 
     break; 
    case 1: 
    case 2: 
     if(other factors2) 
      //add item to next spot in array 
     break; 
    case 3: 
     //add item to next spot in array 
    case 0: 
    case 1: 
    case 2://all cases 
     //add items to next spot in array 
     break; 
    case 1: 
    case 2: 
     if(other factors2) 
      //add item to next spot in array 
     break; 
    case 3: 
     //add item to next spot in array 
    } 

回答

1

你可以用多个switch语句来做到这一点。当您使用break;时,无论如何它都会切断开关块。

1

交换机不适合这种情况,您将需要执行一些if-else语句(或Peter说的一些单独的switch语句)的检查。

JLS

没有两个与switch语句相关联的情况下常量表达式可能具有相同的价值。

3

我会跟你分割伪切换成真正的开关启动:

switch(variable){ 
case 0: 
case 1: 
    if(other factors) 
     //add item to next spot in array 
case 2: 
case 3://all cases 
    //add items to next 3 spots in array for all cases 
} 

switch(variable){ 
case 0: 
case 1: 
    if(other factors) 
     //add item to next spot in array 
case 2: 
case 3://all cases 
    //add more items to next spot in array 
} 

switch(variable){ 
case 1: 
case 2: 
    if(other factors2) 
     //add item to next spot in array 
    break; 
case 3: 
    //add item to next spot in array 
case 0: 

} 

switch(variable){ 
case 1: 
case 2://all cases 
    //add items to next spot in array 
    break; 
case 1: 
case 2: 
    if(other factors2) 
     //add item to next spot in array 
} 

这应该满足你的要求。

然后,我会提取每个开关块在自己的方法,使其更容易理解和阅读。

你可以考虑提取到一个小班hirachy这一切:

class DefaultExecutor{ 
    void do(){ 
     step1(); 
     step2(); 
     step3(); 
     step4(); 
    } 
    void step1(){//all cases class of the first switch statement} 
    //... similar methods for the other switcht statements 
} 

class CaseZeor extends DefaultExecutor{ 
    // override step1-4 as required for special treatment of case 0 
} 

// ... further classes for cases 1-3 
相关问题