2015-05-06 81 views
3

我能够更改java中for循环内的索引吗?例如:在for循环内改变索引

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

虽然这样做在J ++ for循环,里面的for循环中,我也是做当J = J + 3,是否有可能为我做到这一点?

+2

不确定你的意思是“有可能吗?”这是可能的,你已经做到了。 –

+1

这样做在概念上是错误的... – Jameru

+2

当比较字符串(或任何对象)时避免'=='http://stackoverflow.com/questions/513832/how-do-i-compare-strings-in-java – Pshemo

回答

4

是的,你可以改变一个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++; 
}