如何处理此代码?

How is This Code Being Processed?

当我运行以下代码时:

int n = 20;
int result  = (n % 2)-1;
int nextResult = result + 1;

for(int i =0; i < 5; i++)
{ 
  n += 1; nextResult += 1;
  System.out.println("\n" + result + "\n" + nextResult);
} 

我得到以下结果:

20
0

20
1

20
2

20
3

20
4
BUILD SUCCESSFUL (total time: 0 seconds)
  1. resultnextResult 的公式是在每次迭代时求解,还是我只是得到初始结果?

  2. 如果上述查询的答案是前者,那是典型的jvm的int变量处理吗?

  3. 有没有反过来的情况?

变量只有在使用某种 = 设置时才会解析。更改与另一个变量有关系的变量不会更新另一个变量;你必须明确地做到这一点。

int n = 20;
int result  = (n % 2)-1;
int nextResult = result + 1;

for(int i =0; i < 5; i++) { 
    n += 1;
    result = (n % 2)-1; //update result because n changed
    nextResult = result + 1; //update nextResult because result changed
    System.out.println("\n" + result + "\n" + nextResult);
} 

根据我过去与软件新手打交道的经验,我想我知道 OP 困惑的根源是什么。

这是一个程序,而不是数学方程组。这里的关键见解是程序逐行执行。行

int nextResult = result + 1;

是一项作业;它取 result 在特定时刻 的值,将其加一,然后将该值赋给 nextResult。它确实 not 在 result 和 nextResult 之间建立关系,以便后者总是比前者大 1。任何一个变量都可以在不影响另一个的情况下被分配给某个点。

例如,这是一个有效的程序:

a = 1
b = 2;
a = b;

如果你把这个当成一个方程组,那就是废话了。如果您将其视为一系列处理指令 - 计算右侧,分配给左侧的变量,移动到下一行 - 没有错。