对 JAVA 处理此工作流程和参考情况的方式感到困惑。有人可以澄清吗?

Puzzled about the way JAVA handles this workflow and reference situation. Can someone clarify?

我不太确定 java 是如何处理这个简单代码的。我已经设法让它工作了,但我真的不明白为什么会出现这些问题(请参阅代码注释)。

更具体地说:

任何关于此的澄清或对此处使用的密钥 concepts/issues 的引用将不胜感激。

谢谢,CodeAt30

System.Out.println(grow(1));

static int grow(int counter) {

    int newCounter = counter++;
    int limit = 8;

    if (newCounter < limit) {

        System.out.println("Counter: " + counter);
        System.out.println("New Counter: " + newCounter);   
        return counter * grow(counter++);                   // If I use newCounter here I loop out to failure as the number stays static (always under limit)
                                                            // counter++ does work though, providing a good <number>! calculation (7! or 6! etc.).      
    } else if (newCounter % 2 == 0) {                       
                                                            // If I use counter++ instead of newCounter in both "else if" statements though,
        System.out.println("even number");                  // java only catches the first one. An odd number is not caught,
        return 1;                                           // and final "else" statement is invoked. newCounter works well though.

    } else if (newCounter % 2 == 1) {

        System.out.println("odd number");
        return -1;

    } else {                                                // I do not want to reach this final else possibility.

        System.out.println("Got to else.....");
        return 0;

    }
}

你的问题在于理解counter++

++后的变量叫做postfix increment operator。 JLS 的相关部分是:

the value 1 is added to the value of the variable and the sum is stored back into the variable.

The value of the postfix increment expression is the value of the variable before the new value is stored

这意味着counter++也给变量counter赋了一个新值。它基本上是 counter = counter + 1 的缩写。这个区别是 counter++ 也是一个有值的表达式。棘手的部分是,该表达式的值是 counterold 值。 运行 这个小例子说明一下:

public static void main(String[] args) {
    int counter = 0;
    System.out.println(counter++);
    System.out.println(counter);
}

还有prefix increment operator。这里的表达式具有递增的值。

你在这里写的代码的逻辑很难理解,这是因为newCountercounter和你重复调用counter++的原因。

 int newCounter = counter++;

...等同于:

 int newCounter = counter;
 counter = counter + 1;

因此,如果您在 newCounter 初始化后调用 grow(5)

 newCounter == 5
 counter == 6

你在其他地方有:

 return counter * grow(counter++); 

这有点难以推理;相当于:

 int temp1 = counter;
 int temp2 = grow(counter);
 counter = counter + 1;
 counter = temp1 * temp2;

... 所以无论有没有 ++,最终结果都是一样的。或者换个说法,这里的++只会让人更难理解。

某些语言,例如 Python,没有 ++ post 递增运算符,因为设计者认为它会鼓励混淆代码。在我看来,post-increment 确实可以用在干净的代码中,但初学者应该将其使用限制在非常具体的习语中(例如 for(int i=0; i<n< i++))。


在你的递归代码中,你可能需要 final int newCounter = counter + 1.

使用 final 告诉编译器变量的值在此范围内是不可更改的,是使代码更易于推理的有用工具。