简体   繁体   中英

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.

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!

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;

    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM