Change index inside for loop

Is it possible to change the index inside a 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 does j ++ in a for loop, inside a for loop, I also do j = j + 3. Is it possible to do this?

+3


source to share


1 answer


Yes, you can change the index inside the for loop, but it's too confusing. Better to use a while loop in this 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++;
}

      

+4


source







All Articles