Java交换机案件落空

时间:2013-11-23 06:05:44

标签: java switch-statement

我有一个像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;
}

这是一种优雅的方式,没有特殊情况6的功能,案例3-5调用? (我在这里使用int,但这是一个例子,所以我不能使用if(int >2)

5 个答案:

答案 0 :(得分:3)

开关无法真正完全按照您的要求开箱即用。您可以使用嵌套开关构建类似的东西:

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不符合任何内部案例,则可以绕过共享代码。

答案 1 :(得分:2)

我能想到的一种方法是将代码移动到不同的功能。这样的事情。

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;
}

或者您甚至可以针对每个案例采用不同的方法,并在case3()中调用case6()case 3:方法。无论哪种方式,方法解决方案都可以工作,而且恕我直言,它会更加优雅和多个switch语句。

答案 2 :(得分:1)

我不确定它是否优雅,但一种方法是拥有两个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;
}

答案 3 :(得分:1)

虽然你的代码并不漂亮,但它可能会给你带来不错的表现。另一个显而易见的选择是if-elseif-else语句。请参阅接受的答案here,了解为什么切换可能是最佳选择,并here查看使用Java中的大型switch语句可能遇到的性能问题。

答案 4 :(得分:1)

这也可能是您想要实现的目标的解决方案:

       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;
        }

这个想法是你添加一个额外的条件检查,让你的代码落到所有分支而不执行不必要的分支。