简体   繁体   English

与Java教科书中的递归解释相混淆

[英]Confused by Recursion Explanation in Java textbook

So I'm reading a textbook explanation of recursion and I'm getting confused. 因此,我正在阅读教科书中有关递归的解释,这让我感到困惑。 This is the example they use. 这是他们使用的示例。

    public static void message(int n){
        if (n > 0){
            {
                System.out.println("This is a recursive method");
                message(n-1);
            }
        }
    }

Then they create a main method which calls the message method from above when n=5 and explain that the method is called 6 times. 然后他们创建一个main方法,当n = 5时从上面调用message方法,并说明该方法被调用了6次。 The method calls itself 5 times so the depth of recursion is 5. What I don't get is this: "Because there are no more statements to be executed after the method call, the fifth instance of the method returns control of the program back to the fourth instance. This repeats until all instances of the method return." 该方法调用自身5次,因此递归的深度为5。我不明白的是:“由于在该方法调用之后不再需要执行任何语句,因此该方法的第五个实例将返回对程序的控制权到第四个实例。重复直到该方法的所有实例返回为止。”

What do they mean by the method returns? 方法返回它们是什么意思?

It means that the method ends. 这意味着该方法结束。 As the method is void, there is no actual result to return, but you could write it like this. 由于该方法无效,因此没有实际结果要返回,但是您可以这样编写。

public static void message(int n){
    if (n > 0){
        {
            System.out.println("This is a recursive method");
            message(n-1);
        }
    }
    return;
}

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

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