Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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!

>Solution :

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;

    }
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading