5

Am I able to change the index inside the for loop in java? For example:

for (int j = 0; j < result_array.length; j++){
            if (item==" ") {
                result_array[j] = "%";
                result_array[j+1] = "2";
                result_array[j+2] = "0";
                j = j+2;
            }
            else result_array[j] = item;
        }

Although it is doing j++ in the for loop, inside the for loop, i am also doing j = j + 3. Is it possible for me to achieve this?

munmunbb
  • 297
  • 9
  • 22
  • 2
    Not sure what you mean by "is it possible?" It is possible, and you've done it. – Michael Myers May 06 '15 at 22:04
  • 1
    It is conceptually wrong to do that... –  May 06 '15 at 22:04
  • 2
    Avoid `==` when comparing Strings (or any objects) http://stackoverflow.com/questions/513832/how-do-i-compare-strings-in-java – Pshemo May 06 '15 at 22:04
  • Yes, but you might accidentally confuse yourself. – user253751 May 06 '15 at 22:28
  • @MichaelMyers nah.. the code above is wrong. I should have used while loop – munmunbb May 07 '15 at 05:28
  • @WendyMunmunWang: He's not saying anything about the correctness of the code, but about the question 'whether it is possible'. Correctness of the code also depends on whether it does what you're expecting (semantics) in addition to what you can do in code (syntax). Syntactically your code is correct, and your wordings make the question mean more about syntax than semantics. – 0xc0de Oct 06 '16 at 07:10
  • Off topic: An early 3rd GL was FORTRAN. Its design was influenced by a particular computer's machine instructions. The loop construct was `DO LINE INDEX = START, LIMIT, INCR`, where LINE was the label of last line of code in the loop, START was the initial value, LIMIT was the terminating value, and INCR was the increment value. Changing the values of INDEX, START, LIMIT, or INCR while the loop was running would have no effect until the loop exited. – Old Dog Programmer May 22 '22 at 23:27

1 Answers1

7

Yes you can change index inside a for loop but it is too confusing. Better use a while loop in such case.

int j = 0;
while (j < result_array.length) {
    if (item.equals(" ")) {
        result_array[j] = "%";
        result_array[j + 1] = "2";
        result_array[j + 2] = "0";
        j = j + 2;
    } else
        result_array[j] = item;
    j++;
}
MChaker
  • 2,610
  • 2
  • 22
  • 38