change index inside a for loop

痞子三分冷 提交于 2019-12-19 21:41:27

问题


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?


回答1:


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


来源:https://stackoverflow.com/questions/30088401/change-index-inside-a-for-loop

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!