如果声明不工作。我的代码出了什么问题?

时间:2016-06-23 18:26:19

标签: java arrays if-statement arraylist

我是java的初学者,我不知道我的代码有什么问题。非常感谢您的协助。

此代码应检查数组中的任何元素是否小于tc,然后应增加其值。

int pay1  = 190;
int pay2  = 1175;
int pay3  = 455;
int pay4  = 345;
int tc    = 400;
int[] pay = { pay1, pay2, pay3, pay4 };

for(int i = 0; i < pay.length; i++)
{
    if(pay[i] < tc)
    {
        pay[i] = pay[i]++;
        System.out.println(pay[i]+",");
    }
}

1 个答案:

答案 0 :(得分:7)

变化:

pay[i] = pay[i]++;

要:

pay[i]++;

不要尝试修改(++)并在同一行中分配(=)或发生不好的事情。在这种情况下,它执行增量,然后重新分配原始值。

此代码:

int i = 0;
i = i++;

生成此字节码(javap -c):

   0: iconst_0     
   1: istore_1    
   2: iload_1    
   3: iinc 1, 1  
   6: istore_1

这意味着:

0: put zero on the stack
1: put the zero into i
2: put the value of i (0) onto the stack
3: increment i by 1 (i now has a value of 1)
6: store the value on the stack (0) into i (i now has a value of 0)