gpt4 book ai didi

java - 对JAVA处理这个工作流程和引用情况的方式感到困惑。有人可以澄清一下吗?

转载 作者:行者123 更新时间:2023-12-02 13:42:33 25 4
gpt4 key购买 nike

我非常不确定java通过这个简单代码的方式。我已经设法让它工作,但我真的不明白为什么会出现问题(参见代码注释)。

更具体地说:

  • 为什么“newCounter”和“counter++”之间的功能有如此大的差异?

  • 为什么 counter++ 适合递归,而 newCounter 则不然?

  • 为什么java只捕获第一个counter++“else if”条件语句,而不捕获第二个?

  • 当我使用 newCounter 而不是 counter++ 时,为什么 java 会捕获两个“else if”语句我觉得 java 的工作方式中可能有一些我所缺少的重要原则,我应该学习。

对此的任何澄清或对此处所涉及的关键概念/问题的引用将非常感激。

谢谢,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++ 也是一个带有值的表达式。棘手的部分是,该表达式的值是 counter值。运行这个小示例以进行说明:

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

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

关于java - 对JAVA处理这个工作流程和引用情况的方式感到困惑。有人可以澄清一下吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42666472/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com