while 循环内的递归,它是如何工作的? [英] Recursion inside while loop, How does it work?

查看:70
本文介绍了while 循环内的递归,它是如何工作的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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..

推荐答案

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

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

并且陷入循环中,因为在 while 循环的范围内没有任何东西修改 len.第一次调用(使用 len=5、4、3)经过一个循环迭代,然后等待 Strangemethod 返回.当 len=2 时,while 循环调用奇怪方法(1),并且由于 len 不大于 1,while 循环结束并且该调用返回.但是在最底部剩余的 whle 循环中 len 仍然是 2,所以它再次调用了奇怪的方法(2).然后再次.再说一遍.

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() 会比 while() 更合适.

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

这篇关于while 循环内的递归,它是如何工作的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆