我们可以在 switch case 里面有标签吗 java

Can we have label inside switch case java

我有以下带有 4 个案例的开关块的伪代码。在第 4 种情况下,我有 if else 条件,当某些条件满足时,我将列表大小减少 1,它必须再次返回到情况 4 并从第 4 种情况的开头执行。我试图在案例 4 中创建一个标签:但它给出了编译错误。

 switch(choice) {

 case 1:   /* do operations */
          break;
 case 2: /* do operations */
          break;
 case 3: /* do operations */
          break;
 case 4: 
        mylabel:
      if(condition1)  {

       }
       else if(condition2) {

       }
       else {
        break mylabel;
       }
       break;
default : 
}

以上代码给出了编译错误。但我希望程序流程是这样的。所以我尝试了以下代码:

switch(choice) {

case 1:   /* do operations */
          break;
case 2: /* do operations */
          break;
case 3: /* do operations */
          break;
case 4: 
        if(condition1)  {

       }
       else if(condition2) {

       }
       else {
        break case 4;
       }
       break;
  default : 
  }

上面的代码仍然存在,我面临编译问题。有没有其他方法可以实现同样的目标。在这里,我需要回到我要中断的同一个案例陈述的开头。因此它是不同的。

    public void switchFunction(String choice){ 
      switch(choice) { 
        case 1:   
          do1();
          break; 
        case 2: /* do operations */
          break; 
        case 3: /* do operations */
          break; 
        case 4: 
          recursiveFunction();
          break;   
        default :
      } 
    }

    public void recursiveFunction(){ 
      if(condition1){
        doSomething(); 
      }
      else if(condition2){
        doSomethingElse();
     }
    else{
     /* You can call it as much as you want! */
    recursiveFunction();

} }

使用标签和 while 循环。它会起作用

switch (choice) {
    case 1:   /* do operations */
      break;
    case 2: /* do operations */
      break;
    case 3: /* do operations */
      break;
    case 4:
        mylabel:{
            while(true){
                   if(condition1)  {

                   }else if(condition2) {

                   }else {
                       break mylabel;// breaks the while-loop
                   }
             }
         }
     default:
         break;
   }