更改for循环内的索引 [英] change index inside a for loop

查看:239
本文介绍了更改for循环内的索引的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我能够改变在Java的for循环内的索引?例如:

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





虽然在for循环中执行j ++,但是在for循环中,我我也在做j = j + 3。我能做到这一点吗?是的,你可以改变一个for循环内的索引,但它太混乱了。在这种情况下最好使用while循环。

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


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?

解决方案

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

这篇关于更改for循环内的索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆