munmunbb
munmunbb

Reputation: 417

change index inside a for loop

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?

Upvotes: 5

Views: 7753

Answers (1)

MChaker
MChaker

Reputation: 2649

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++;
}

Upvotes: 8

Related Questions