如何用Java编写递归方法 [英] how to write recursive method in Java

查看:112
本文介绍了如何用Java编写递归方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请检查此代码段.

我使它递归,但不起作用.它再次进入该方法,但是在这两者之间不执行该语句.

Please check this code snippet.

I made it recursive but it doesn''t work. It enters the method again but it doesn''t execute the statement in between.

int check_month(int a)
{
    if(a>12)
    {
        a-=12;y1++;
        if(a>12)
        {
            //y1++;
            System.out.println("check");
            check_month(a);
        }
    }
    System.out.println("exit");
    return a;
}



请检查并让我知道该错误.



这是一个好问题/主题吗? 0


OP的回复-从答案中移到此处,因为已删除. -亨利

通过以下计算检查代码
最初是a = 50
输入方法,a> 12 = true
输入if块. a = a-12;即50-12 = 38. a = 38
再次输入是否为2. a> 12,即38> 12.递归过程称为.开始.
再次a = 38
a> 12,a = a-12,即38-12 = 26,a = 26;
再次输入是否为2. a> 12,即26> 12.递归过程称为.开始.
再次a = 26
a> 12,a = a-12,即26-12 = 14 a = 14;
再次输入是否为2. a> 12,即14> 12.递归过程称为.开始.
再次a = 14
a> 12,a = a-12,即14-12 = 2,a = 2;
返回2;
它应该像这样工作,但不是..... !!!

[/Edit]



Please check and let me know the error.



Is This A Good Question/Topic? 0


Response from OP - moved here from an answer, since deleted. - Henry

check the code with following calculation
initially a=50
enters method, a>12=true
enters if block. a=a-12;ie 50-12=38. a=38
again enters if 2 . a>12 ie 38>12. recursive procedure called. goes to start.
again a=38
a>12, a=a-12, ie 38-12=26, a=26;
again enters if 2 . a>12 ie 26>12. recursive procedure called. goes to start.
again a=26
a>12, a=a-12, ie 26-12=14 a=14;
again enters if 2 . a>12 ie 14>12. recursive procedure called. goes to start.
again a=14
a>12, a=a-12, ie 14-12=2, a=2;
return 2;
it should work like this , but it doesn''t.....!!!

[/Edit]

推荐答案

很难说代码需要做什么,但第10行可能应该是return check_month(a);第6行的测试也看起来是错误的,这可能是多余的.
It is difficult to say what the code needs to do, but line 10 should probably be return check_month(a); The test at line 6 looks wrong too, it is probably redundant.


我注意到的一件事是您在if语句中的递归调用未将其返回值设置为任何值.自从我做完任何Java以来​​已经有一段时间了,但是我相信传递的参数"int a"是每次调用函数时它自己的实例.因此,第一次调用此函数的参数"a"与下一次调用此函数的参数"a"不同.

尝试将if语句中的递归行更改为:

a = check_month(a);
One thing I notice is your recursive call in the if statement does not set its return value to anything. Its been a while since I''ve done any java, but I believe the passed parameter "int a" is its own instance with each call to the function. So the "a" parameter in the first call to this function is not the same variable as the "a" in the next call to this function.

Try changing your recursive line in the if statement to:

a = check_month(a);


这篇关于如何用Java编写递归方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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