0

In this loop there's an error "The value changed at i++ is not used".

for (technique j : activeuser.techniques) {
    int i = 1;
    i = i++;
    System.out.print(i + j.tname + " and ");
}

The context here is not important, so I don't write the rest of the code. Can you explain how this loop exactly works? I understand other loops, but can not find explanation for that one, thank you.

Hien Nguyen
  • 24,551
  • 7
  • 52
  • 62
Syejsjc
  • 11

3 Answers3

1

You need defined i variable outside of for loop and dont need assing i = i++;

int i = 1;
for( technique j : activeuser.techniques  ) {                  
    i++;
    System.out.print(i + j.tname + " and ");

 }
Hien Nguyen
  • 24,551
  • 7
  • 52
  • 62
  • 1
    "*and dont need assing `i = i++;`* - Not only is it not needed, but a bug since `i = i++` will have no visible effect (due to the postincrement). – Turing85 May 01 '20 at 06:34
0
      for( technique j : activeuser.techniques  ) {
            int i = 1;  // for every loop you are resetting the i's value to 1
            i = i++;   // it is expanded to i = i; i=i+1;
            System.out.println("---"+i);
            System.out.println(i + j.tname + " and ");

        }

QuickSilver
  • 3,915
  • 2
  • 13
  • 29
0

Note the following points about the postfix change (increment/decrement) operator:

  1. A postfix operator assigns the value to the left operand and then change its value.
  2. If the variable of the left operand is different from that of the right operand, the variable of the left operand will have the original value of the variable with the postfix (i.e. the variable of the right operand) and the variable of the right operand will have the changed value.
  3. If the variable of the left operand is the same as that of the right operand, the variable will continue to have the original value i.e. the change won't have any effect. Although technically allowed, it's confusing and can cause bugs in your program/application.

In your case, you have done what is mentioned in point#3. After this assignment, i will continue to have the value, 1.

int i = 1;
i = i++;

Apart from this, since you have put these two lines under a loop, every time the loop will iterate, the variable, i will be freshly created. In other words, old i dies and a new i is born with the initial value of 1.

However, even if you declare i outside the loop but assign the value, 1 to it (i.e. i = 1), its value will be reset in eadh iteration of the loop. If you intend to preserve the value of i, you need to declare and initialize it outside the for loop e.g. as follows:

int i = 1;
for (technique j : activeuser.techniques) {                  
    i++;
    System.out.print(i + j.tname + " and ");
}

Note that since you are not assigning the value of i to any variable, using ++i or i = i + 1 will have the same effect in the code given above.

Arvind Kumar Avinash
  • 71,965
  • 6
  • 74
  • 110