-1

I'm a beginner with java and I don't know whats wrong with my code. Your assistance will be highly appreciated.

This code should check if any element of the array is less than tc, then its value should be incremented.

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]+",");
    }
}
TofuBeer
  • 60,850
  • 18
  • 118
  • 163
ROY
  • 3
  • 4

1 Answers1

7

Change:

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

To:

pay[i]++;

Don't try to modify (++) and assign (=) in the same line or bad things happen. In this case it does the increment, then reassigns the original value.

This code:

int i = 0;
i = i++;

Produces this bytecode (javap -c ):

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

Which means:

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)
TofuBeer
  • 60,850
  • 18
  • 118
  • 163