简体   繁体   English

跳出for循环,包括带有for循环的递归方法(Java)

[英]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).我的main方法有一个for循环,里面有一个递归方法,递归方法也有一个for循环(递归方法基本上替代了很多嵌套的for循环)。 When a specific case is reached, I want to jump out of the recursive method and out of the for-loop in my main.当遇到特定情况时,我想跳出递归方法并跳出 main 中的 for 循环。 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;因为我不能 label 我的主循环并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.在我的方法中(据我所知),我尝试使用 boolean,但由于 for 循环和/或递归调用,boolean 切换回来并且没有想要的效果。

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.您可能想从递归方法中返回 boolean 。 E. g.例如。 true means that recursive call8ng should stop and exit loop true 表示递归 call8ng 应该停止并退出循环

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;

    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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