1

I have below pseudocode code with switch block with 4 cases. In 4th case I have if else conditions and when some condition satisfies, I am reducing list size by 1 and it has to come back to case 4 again and execute from the beginning of the 4th case. I tried to create a label in case 4: but it is giving the compilation error.

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

Above code gives the compilation error. But I want the program flow to be something like that. So I tried below code:

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

With above code still, I am facing compilation issues. Is there any alternative for achieving the same. Here I need to go back to the beginning of the same case statement from where I will break. Hence it is different.

Babanna Duggani
  • 737
  • 2
  • 12
  • 34

2 Answers2

1

use label and while loop. it will work

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;
   }
jitendra varshney
  • 3,484
  • 1
  • 21
  • 31
0
    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();

} }