代码:
import org.apache.commons.lang.ArrayUtils;
int[] arr = new int[] { 2, 3, 4, 5, 6, 7, 8 };
int index = 0;
for (int whit : arr) {
if (whit % 2 == 0)
arr = ArrayUtils.remove(arr, index);
index++;
}
错误:
Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 6, Length: 4
Java版本: 1.7
有人可以帮我安全地循环吗? 提前谢谢。
我在这里提到的大部分问题都是数组而没有任何帮助。
它看起来很简单,但它不起作用。如果错误,请评论问题。
答案 0 :(得分:2)
您必须更改代码,因为当您从数组中删除数字时,您不必增加索引计数器:
int index = 0;
for (int whit : arr) {
if (whit % 2 == 0)
arr = ArrayUtils.remove(arr, index);
else
index++;
}
答案 1 :(得分:0)
使用IntStream
可以更轻松地完成此操作。
int[] arr = new int[] { 2, 3, 4, 5, 6, 7, 8 };
arr = Arrays.stream(arr).filter(n -> n%2!=0).toArray();
结果:
{3, 5, 7}
如果您无法使用流,可以通过以下方式使代码正常工作:
int index = 0;
while (index < arr.length) {
if (arr[index] % 2 == 0) {
arr = ArrayUtils.remove(arr, index);
} else {
++index;
}
}
请注意,如果删除了某个元素,则不会增加index
,因为所有后续元素都已被移回一个位置。
答案 2 :(得分:0)
使用for循环你可以这样做:
int[] arr = new int[]{2, 3, 4, 5, 6, 7, 8};
for (int index = 0; index < arr.length; index++) {
int whit = arr[index];
if (whit % 2 == 0) {
arr = ArrayUtils.remove(arr, index);
index--;
}
}
答案 3 :(得分:0)
你也可以使用do-while-loop:
int[] arr = new int[]{2, 3, 4, 5, 6, 7, 8};
int index = 0;
do{
if (arr[index] % 2 == 0) {
arr = ArrayUtils.remove(arr, index);
} else {
index++;
}
}while(index < arr.length);
答案 4 :(得分:-1)
在提交我的答案之后,我看到你改变了你的初始帖子只包括Java 1.7 - 但是我的是1.8。我只想提一下。
然后调用toArray()将其转换回数组。
import java.util.Arrays;
int[] arr = new int[] { 2, 3, 4, 5, 6, 7, 8 };
arr = Arrays.stream(arr).filter(a->a%2==0).toArray();
System.out.println(Arrays.toString(arr));