我正在学习递归,我运行了这个函数来跟踪"count"变量,看看它在递归过程中是如何变化的.在收到4串"你好"之后.在计数已经是0之后,我想要判断计数发生了什么.我发现它实际上是递增1,但我不知道为什么它会递增.为什么在将计数设置为0之后,计数会递增?在终止递归后,它是否恢复到其原始值?

public class Main {
    public static void main(String[] args) {
         
        sayHi(4);
    }

    public static void sayHi(int i) {
        int count = i;
        System.out.println(count);
        if(count == 0) return;


        System.out.println("hi!");
        sayHi(count - 1);

        System.out.println(count);

        System.out.println("Hello.");


    }
}

以下是代码的输出:

OUTPUT: 

4
hi!
3
hi!
2
hi!
1
hi!
0
1
Hello.
2
Hello.
3
Hello.
4
Hello.

推荐答案

它不是递增的,事实上,count的值根本不会改变. 它只是被输出了两次:

int count = i;
System.out.println(count); // <--- first here
if(count == 0) return;

System.out.println("hi!");
sayHi(count - 1);

System.out.println(count); // <--- then here
System.out.println("Hello.");

这两个是递归发生的地方.因此,在输出中:

4    // these
hi!  // are
3
hi!
2
hi!
1
hi!
0
1
Hello.
2
Hello.
3
Hello.
4      // the outermost
Hello. // method call

以及:

4
hi!
3    // these
hi!  // are
2
hi!
1
hi!
0
1
Hello.
2
Hello.
3      // the second outermost
Hello. // method call
4
Hello.

直到:

4
hi!
3
hi!
2
hi!
1
hi!
0    // this is the innermost method call
1
Hello.
2
Hello.
3
Hello.
4
Hello.

递归没有什么特别之处,新的开发人员往往会过度考虑它.该方法本身不会做任何特别复杂的事情.暂时忽略它是递归的,只判断它的作用:

int count = i;                // declare a value, which never changes
System.out.println(count);    // output that value
if(count == 0) return;        // conditionally return (the innermost does this)

System.out.println("hi!");    // output 一根线
sayHi(count - 1);             // call a method, which itself may generate lots of output

System.out.println(count);    // output the same value again
System.out.println("Hello."); // output 另一个字符串

因此,除非传递给该方法的值为0,否则每次调用该方法都会产生四行输出:

  • 传递给它的号码
  • 一根线
  • 传递给它的号码 again
  • 另一个字符串

因此,对于没有传递值0的方法的任何调用,应该会看到传递给它的值输出两次.

Java相关问答推荐

在URL类图中表示Java swing类

转换为Biggram

Java WireMock定义存根在Cucumber并行执行的多线程测试中失败

使用Java Streams API比较两个不同的Java集合对象和一个公共属性

在Java Stream上调用collect方法出现意外结果

在for—each循环中的AnimationTimer中的if语句'

Java函数式编程中的双值单值映射

路径映射未发生

从ActiveMQ Classic迁移到ActiveMQ Artemis需要进行哪些客户端更改?

如何只修改父类ChroniclerView位置0处的第一个嵌套ChroniclerView(child)元素?

try 从REST API返回对象列表时出错

try 在Android Studio中的infoWindow中使用EditText(Java)

Kotlin Val是否提供了与Java最终版相同的可见性保证?

如何在Java springboot中从一个端点发送多个时间响应?

如何从命令行编译包中的所有类?

没有Tomcat,IntelliJ如何在本地运行API?

通过/失败的参数化junit测试方法执行数

在Spring Boot中使用咖啡因进行缓存-根据输出控制缓存

可以';不要在Intellij IDEA中使用最新的Java版本(JDK 21)

如何使用java区分以下结果