简体   繁体   English

为什么在这段递归代码中执行 println?

[英]Why println is being executed in this recursive piece of code?

In this code arrLength starts with four and then keeps being decremented until it reaches zero.在这段代码中,arrLength 从 4 开始,然后一直递减直到达到零。 At the moment it reaches zero it should not execute what is inside the if block anymore.在它达到零的那一刻,它不应该再执行 if 块内的内容。 But what is happening is that when it reaches zero it still executes the println line.但实际情况是,当它达到零时,它仍然执行 println 行。 Not understanding how that println line is being executed since that line is inside the if block and nothing inside the if block should execute when arrLength gets to zero.不了解该 println 行是如何执行的,因为该行位于 if 块内,并且当 arrLength 变为零时,if 块内的任何内容都不应该执行。 At the end it prints 5, 6, 2, 1 while in my understanding it should print nothing never executing the println line.最后它打印 5, 6, 2, 1 而在我的理解中它应该不打印任何东西而不会执行 println 行。

class ArrayElements{
 
    public void printElements(int arr[], int arrLength){
        if(arrLength != 0){
            arrLength--;
            printElements(arr, arrLength);
            System.out.println(arr[arrLength]);
        }
    }
}
public class Main {
 
    public static void main(String[] args) {
        int arr[] = {5,6,2,1};
        int arrLength = arr.length;
 
        ArrayElements mv = new ArrayElements();
        mv.printElements(arr, arrLength );
    }
}

An easy way to understand what is happening is to modify your printElements method like this:了解正在发生的事情的一种简单方法是像这样修改 printElements 方法:

public void printElements(int arr[], int arrLength){
    System.out.println("arrLength value is " + arrLength);
    if(arrLength != 0){
        arrLength--;
        printElements(arr, arrLength);
        System.out.println(arr[arrLength]);
    }
}

The output will be: output 将是:

arrLength value is 4
arrLength value is 3
arrLength value is 2
arrLength value is 1
arrLength value is 0
5
6
2
1

As you can see you made 5 recursives calls but only print 4 values.如您所见,您进行了 5 次递归调用,但只打印了 4 个值。 The reason been the second println is not executed when arrLength is equal to 0.原因是当 arrLength 等于 0 时不执行第二个 println。

This means that when arrLength is 0 you do not enter the if condition.这意味着当 arrLength 为 0 时,您不进入 if 条件。

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

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