【问题标题】:Can we have label inside switch case java [duplicate]我们可以在switch case java中添加标签吗?
【发布时间】:2017-06-13 20:45:06
【问题描述】:

我有以下带有 4 个案例的带有 switch 块的伪代码。在第 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 : 
  }

上面的代码仍然存在,我面临编译问题。是否有任何替代方法可以实现相同的目标。在这里,我需要回到我将要中断的同一 case 语句的开头。因此它是不同的。

【问题讨论】:

  • 我希望您只需将 case 4 代码包装在 do { ... } while (cond) 循环中。

标签: java switch-statement label conditional break


【解决方案1】:
    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();

} }

【讨论】:

    【解决方案2】:

    使用标签和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;
       }
    

    【讨论】:

    • 我能够使用此解决方案返回标签。但是我在标签内没有循环就做到了。谢谢
    • 欢迎您,您也可以不使用循环
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-02-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多