Home > Mobile >  Jumping out of for-loop including a recursive method with for-loop (Java)
Jumping out of for-loop including a recursive method with for-loop (Java)

Time:12-30

This is my first post, so sorry if I post incorrect or incomplete, I will answer every question and I am open for improvements.

My main method has a for-loop with a recursive method in it, the recursive method also has a for-loop (the recursive method basically replaces a lot of nested for-loops). When a specific case is reached, I want to jump out of the recursive method and out of the for-loop in my main. For visualization:

public static void main(..)

for (int i = 0, i < 100 ; i  ) {
   //do something
   recursivemethod(...)
}
//jump here, if case in method is reached
------------------------
recursivemethod (...) 
for (int i = 0; i < 10 ; i  ) {
    //do something
    if (case reached) {//jump out of loop in main}
    else {recursivemethod(modified)}
    
}

As I cannot label my for-loop in main and break Label; in my method (to my knowledge), I tried using a boolean, but because of for-loops and/or recursive call, boolean switches back and has not the wanted effect.

There was a similar question where the user later added his solution, but didn't specify it enough for me to understand and how to implement this in my code, the user was last seen years ago, so I cannot ask him. Can someone please help me?

Thanks a lot in advance!

CodePudding user response:

You probably want to return boolean from your recursive method. E. g. true means that recursive call8ng should stop and exit loop

for (int i = 0, i < 100 ; i  ) {
    //do something
    if(recursivemethod(...))
        break;
 }

Recursive method

boolean  recursivemethod (...) {
    for (int i = 0; i < 10 ; i  ) {
    //do something
    if (case reached) {return true;}
    else {return recursivemethod(modified)}
    return false;

    }
}
  • Related