while循环内的递归,它是如何工作的?

发布于 2024-09-06 19:36:10 字数 398 浏览 6 评论 0原文

你能告诉我这段java代码是如何工作的吗? :

public class Main {
    public static void main (String[] args)  {
        Strangemethod(5);
    }
    public static void Strangemethod(int len) {
        while(len > 1){
            System.out.println(len-1);
            Strangemethod(len - 1);
        }
}
}

我尝试调试它并一步步按照代码操作,但我不明白。

更新:抱歉,我没有提到我知道这段代码的结果,只是想知道执行的步骤。

Can you please tell me how does this java code work? :

public class Main {
    public static void main (String[] args)  {
        Strangemethod(5);
    }
    public static void Strangemethod(int len) {
        while(len > 1){
            System.out.println(len-1);
            Strangemethod(len - 1);
        }
}
}

I tried to debug it and follow the code step by step but I didn't understand it.

update: sorry I didn't mention that I know the result of this code but just want to know the steps of the execution..

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(8

友谊不毕业 2024-09-13 19:36:10

这将打印 4 3 2 1 1 1 1 1 1...

并陷入循环,因为在 while 循环范围内没有任何内容修改 len 。第一个调用(len=5、4、然后 3)经历一个循环迭代,并等待 Strangemethod 返回。当len=2时,while循环调用strangemethod(1),并且由于len不大于1,因此while循环结束并且该调用返回。但在最底层的剩余 whle 循环中 len 仍然是 2,因此它再次调用了 oddmethod(2)。又来了。又来了。

if() 比 while() 更合适。

That'll print 4 3 2 1 1 1 1 1 1...

And get stuck in a loop because nothing ever modifies len in the scope of the while loop. The first calls (with len=5, 4, then 3) go through one loop iteration, and are left waiting for Strangemethod to return. When when len=2, the while loop calls strangemethod(1), and since len is not greater than 1, the while loop finishes and that call returns. But len is still 2 in the bottom-most remaining whle loop, so it calls strangemethod(2) again. And again. And again.

if() would've been more appropriate than while().

深居我梦 2024-09-13 19:36:10

如果我没记错的话,这不是导致无限循环吗?

一旦奇怪方法(1)返回,奇怪方法(2)将再次打印1,然后再次调用奇怪方法(1)。

您是否忘记在奇怪的方法调用后递减 len ?

If I'm not mistaken, isn't this causing an infinite loop?

Once strangemethod(1) returns the strangemethod(2) would print 1 again and then call strangemethod(1) again.

Are you forgetting to decrement len after the strangemethod call?

浅唱ヾ落雨殇 2024-09-13 19:36:10

编辑:抱歉,第一个回复没有
意识到这一点..它将导致无限
循环

这是一个简单的流程 -
例如 len =5

 public static void Strangemethod(5) {
            while(5 > 1){
                System.out.println(5-1);
                Strangemethod(5 - 1);
            }
public static void Strangemethod(4) {
            while(4 > 1){
                System.out.println(4-1);
                Strangemethod(4 - 1);
            }
public static void Strangemethod(3) {
            while(3 > 1){
                System.out.println(3-1);
                Strangemethod(3 - 1);
            }
    public static void Strangemethod(2) {
            while(2 > 1){
                System.out.println(2-1);
                Strangemethod(2 - 1);
            }
    public static void Strangemethod(1) {
            while(1 > 1){//goes back to original(above) call and then an infinite loop since len was never  decremented

            }

打印 4 3 2 1 1.....

EDIT :SORRY For the first reply didnt
realise it..it will cause an infinite
loop

Here is a simple flow -
for e.g len =5

 public static void Strangemethod(5) {
            while(5 > 1){
                System.out.println(5-1);
                Strangemethod(5 - 1);
            }
public static void Strangemethod(4) {
            while(4 > 1){
                System.out.println(4-1);
                Strangemethod(4 - 1);
            }
public static void Strangemethod(3) {
            while(3 > 1){
                System.out.println(3-1);
                Strangemethod(3 - 1);
            }
    public static void Strangemethod(2) {
            while(2 > 1){
                System.out.println(2-1);
                Strangemethod(2 - 1);
            }
    public static void Strangemethod(1) {
            while(1 > 1){//goes back to original(above) call and then an infinite loop since len was never  decremented

            }

Prints 4 3 2 1 1.....

层林尽染 2024-09-13 19:36:10

我知道我已经迟到了将近 13 年,但是我在大学的一次测验中遇到了这个问题,我回答错了,而且我不明白为什么会出现这样的情况。所以我花了一些时间,我相信我可以用一种对每个人都有意义的方式来解释它。

Iteration #1. 方法调用中声明的 while 循环 oddMethod(5);

    public static void strangeMethod(5) {
        while (5> 1) {
            System.out.println(4);
            strangeMethod(4);
        }
    }

因为 5 大于 1,所以 while 块中的代码被执行,所以,现在我们可以在控制台中看到 print 语句,但这里真正重要的是你要注意,是我们没有运行第二个这个 while 循环的迭代,事实上,我们甚至没有完成第一次迭代,它中途暂停了,以便它可以执行奇怪方法(4)的递归调用,并且它永远没有机会完成

确保我们在同一页面上,您对“在调用 oddMethod(5); 中执行了多少次 while 循环迭代完成?”这个问题的回答应该甚至不是一次迭代

但是,我们确实调用了 oddMethod(4);现在这是一个新的方法调用,其中的 while 循环将开始执行,因为满足其继续条件,4 大于 1,但是,就像之前的调用一样,它甚至不会完成一次迭代,并且会调用奇怪的方法(3);

Iteration #1. 方法调用中声明的 while 循环 oddMethod(4);

    public static void strangeMethod(4) {
        while (4 > 1) {
            System.out.println(3);
            strangeMethod(3);
        }
    }

Iteration #1. 方法调用中声明的 while 循环 oddMethod(3);

    public static void strangeMethod(3) {
        while (3 > 1) {
            System.out.println(2);
            strangeMethod(2);
        }
    }

Iteration #1. 方法调用中声明的 while 循环 oddMethod(2);

    public static void strangeMethod(2) {
        while (2 > 1) {
            System.out.println(1);
            strangeMethod(1);
        }
    }

现在,调用 oddMethod(2);是不同的,因为它是唯一一次对 oddMethod() 实际上会迭代多次的调用。

您会看到,while 循环的继续条件是,如果 2 大于 1,这将始终为 true,就像之前的所有调用一样。这个方法的不同之处在于,strangeMethod(1); call 不会中断并暂停 while 循环,它会开始执行,看到没有满足继续条件 while (1 > 1),并且由于在 oddMethod(1) 的调用中没有其他代码;为了让它执行,strangeMethod(1);实际上会完成,允许我们从上次停下的地方继续,即完成 oddMethod(2) 的迭代#1;开始奇怪方法(2)的迭代#2;检查 while 循环的继续条件 (2>1) 是否仍然成立,执行 print 语句,执行 oddMethod(1);调用将完成,并允许我们开始奇怪方法(2)的迭代#3;由于我们没有 len == 1 时的基本情况,所以 oddMethod(2);将无限期地迭代。

因此,调用了 oddMethod(2);其独特之处在于,其中要执行的所有代码实际上都会被执行,从而允许其中的 while 循环进行迭代。

Iteration #2. 方法调用中声明的 while 循环 oddMethod(2);

    public static void strangeMethod(2) {
        while (2 > 1) {
            System.out.println(1);
            strangeMethod(1); //Is now just some dead code 
        }
    }

Iteration #3. 方法调用中声明的 while 循环 oddMethod(2);

    public static void strangeMethod(2) {
        while (2 > 1) {
            System.out.println(1);
            strangeMethod(1); //Is now just some dead code 
        }
    }

现在,如果这仍然没有创造出啊哈!现在,请考虑执行以下操作,通过添加一个简单的 if 块来调整代码

    public static void strangeMethod(2) {
                if (len == 1) {
                        System.out.println(
                                "strangemethod(1) was executed and finished, 
                                The while loop within it did not run 
                                because its condition was not met
                                Thus, allowing us to move on to the second
                                Iteration of the while loop within 
                                strangeMethod(2);"
                        );
                }
        while (2 > 1) {
            System.out.println(1);
            strangeMethod(1);
        }
    }

    public static void strangeMethod(2) {
                if (len == 1) {
                    System.exit(0); // which will end all the previous 
                                    // method calls, unlike return; which will 
                                    // only end strangeMethod(1); but keep 
                                    // strangeMethod(2) still active and                                    
                                    // running
                }
        while (2 > 1) {
            System.out.println(1);
            strangeMethod(1);
        }
    }

对于任何认为我的答案有帮助的人,如果您愿意投票,我将不胜感激。< /强>

I know that I'm almost 13 years late to the party, but I ran into this problem in a quiz at my college, I answered it wrong and I couldn't figure out why it's behaving like this. So I took some time and I believe I can explain it in a way that would make sense to everyone.

Iteration #1. of the while loop declared inside the method call strangeMethod(5);

    public static void strangeMethod(5) {
        while (5> 1) {
            System.out.println(4);
            strangeMethod(4);
        }
    }

Because 5 is greater than 1, the code within the while block got executed, so, now we can see the print statement in the console, but what's really important for you to notice here, is that we did not run a second iteration of this while loop, in fact, we did not even finish the first iteration, it got paused midway so that it can execute the recursive call of strangeMethod(4), and it will never get a chance to finish

To make sure we're on the same page, your answer to the question "how many iterations of the while loop executed in the call strangeMethod(5); completed?" should be not even one iteration.

BUT, we did call strangeMethod(4); now this is a fresh method call, the while loop within it will start to execute since its continuation condition is met, 4 is greater than 1, BUT, just as the previous call, it will not even finish a single iteration and it will call strangeMethod(3);

Iteration #1. of the while loop declared inside the method call strangeMethod(4);

    public static void strangeMethod(4) {
        while (4 > 1) {
            System.out.println(3);
            strangeMethod(3);
        }
    }

Iteration #1. of the while loop declared inside the method call strangeMethod(3);

    public static void strangeMethod(3) {
        while (3 > 1) {
            System.out.println(2);
            strangeMethod(2);
        }
    }

Iteration #1. of the while loop declared inside the method call strangeMethod(2);

    public static void strangeMethod(2) {
        while (2 > 1) {
            System.out.println(1);
            strangeMethod(1);
        }
    }

Now, the call of strangeMethod(2); is different, because it is the only call of strangeMethod() that will actually get to iterate more than once.

You see, the continuation condition for the while loop is, if 2 is greater than 1 which will always be true, just like all the previous call have been. The difference in this method is that the strangeMethod(1); call will not interrupt and pause the while loop, it will start executing, see that the continuation condition while (1 > 1) is not met, and since there is no other code in the call of strangeMethod(1); for it to execute, strangeMethod(1); will actually finish, allowing us to proceed from where we left off, which is to finish iteration #1 of strangeMethod(2); start iteration #2 of strangeMethod(2); check that the continuation condition for the while loop (2>1) still holds true, execute the print statement, execute the strangeMethod(1); call which will finish, and allows us to start iteration #3 of strangeMethod(2); and since we have no base case for when len == 1, strangeMethod(2); will keep iterating indefinitely.

So, the call of strangeMethod(2); is unique in that all the code to be executed within it will actually get executed, allowing the while loop within it to iterate.

Iteration #2. of the while loop declared inside the method call strangeMethod(2);

    public static void strangeMethod(2) {
        while (2 > 1) {
            System.out.println(1);
            strangeMethod(1); //Is now just some dead code 
        }
    }

Iteration #3. of the while loop declared inside the method call strangeMethod(2);

    public static void strangeMethod(2) {
        while (2 > 1) {
            System.out.println(1);
            strangeMethod(1); //Is now just some dead code 
        }
    }

Now, if this is still not creating that AHA! moment, consider doing the following, adjust the code by adding a simple if block

    public static void strangeMethod(2) {
                if (len == 1) {
                        System.out.println(
                                "strangemethod(1) was executed and finished, 
                                The while loop within it did not run 
                                because its condition was not met
                                Thus, allowing us to move on to the second
                                Iteration of the while loop within 
                                strangeMethod(2);"
                        );
                }
        while (2 > 1) {
            System.out.println(1);
            strangeMethod(1);
        }
    }

OR

    public static void strangeMethod(2) {
                if (len == 1) {
                    System.exit(0); // which will end all the previous 
                                    // method calls, unlike return; which will 
                                    // only end strangeMethod(1); but keep 
                                    // strangeMethod(2) still active and                                    
                                    // running
                }
        while (2 > 1) {
            System.out.println(1);
            strangeMethod(1);
        }
    }

For anyone who finds my answer helpful, I would greatly appreciate it if you'd up-Vote it.

人生戏 2024-09-13 19:36:10

您没有说出您希望代码做什么。但是,值得注意的是,len 变量不会更改 Strangemethod 方法中的值 - 它可以被声明为 final。可能您想要做的是使用 --len; 递减它(相当于 len = len - 1;)。

You don't say what you expect the code to do. However, the obvious point of note that the len variable does not change value within the Strangemethod method - it could have been declared final. Possibly what you wanted to do was decrement it with --len; (equivalent to len = len - 1;).

挽梦忆笙歌 2024-09-13 19:36:10

尝试在 Strangemethod(len - 1); 之后添加 len--;。那么它不会让你陷入无限循环。或者,你可以这样做

System.out.println(--len);
Strangemethod(len);

Try adding len--; after Strangemethod(len - 1);. It won't send you into an infinite loop then. Alternatively, you could do

System.out.println(--len);
Strangemethod(len);
关于从前 2024-09-13 19:36:10

这段代码将永远循环。

len - 1 的结果永远不会存储在 while 循环中,因此它无法退出,当 len = 2 时,它只会坐在那里输出 1。

在递归函数中使用 while 的情况并不常见。我通常希望在其位置看到一个 if ,这将为您提供输出:

4
3
2
1

如果您确实需要 while 那么我会像这样重写循环:

while(len > 1)
{
  len--;
  System.out.println(len);
  Strangemethod(len);
}

这将输出:

4
3
2
1
1
2
1
1
3
2
1
1
2
1
1

This code will loop forever.

The result of len - 1 is never stored in the while loop so it can't exit and when len = 2 it'll just sit there outputting 1s.

It's unusual to use a while in recursive functions. I'd typically expect to see an if in its place, which would give you the output:

4
3
2
1

If you really do need the while then I'd rewrite the loop like this:

while(len > 1)
{
  len--;
  System.out.println(len);
  Strangemethod(len);
}

This will output:

4
3
2
1
1
2
1
1
3
2
1
1
2
1
1
网名女生简单气质 2024-09-13 19:36:10

另外,我认为有人应该指出 len 永远不会递减,所以你会得到一个无限循环。我发现到目前为止只有 7 人提到过这一点。

Also, I think someone should point out that len is never decremented so you get an infinite loop. I see that only 7 people have mentioned that so far.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文