2011-11-24 6 views
1

나는 스위치 또는 뭔가 다른 케이스에서 여러 번 호출 할 수있는 자바 코드를 작성하고 싶습니다. 중간에 대부분 또는 모든 케이스에 대해 동일한 코드를 사용합니다. 지금은 대소 문자를 구분하는 코드로 둘러 쌓여 있기 때문에 각각의 경우에 대해 코드의 절반을 반복해야합니다. 내 마음의 코드는, 그냥 내가 존재하는 경우는 아마 휴식 이외의 어떤 것을 이해하는 경우에 다음 호출 할 때까지 실행을 중지 의미 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에서

:

스위치 문으로 연결된 경우 상수 식의 아니 두 사람은 같은 값을 가질 수있다.

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 
관련 문제