这里有什么问题?我想从数组中删除一个项目,但它显示给我
error ArrayIndexOutBound exception
public class delete {
public static void main(String[]args) {
int i;
//delete item from array
int k[] = new int[]{77,99,44,11,00,55,66,33,10};
//delete 55
int searchkey=55;
int nums=k.length;
for ( i=0;i<nums;i++)
if (k[i]==searchkey)
break;
for (int t=i;t<nums;t++)
k[t]=k[t+1];
nums--;
for (int m=0;m<nums;m++) {
System.out.println(k[m]);
}
}
}
最佳答案
for (int t=i;t<nums-1;t++) //Should be -1 here, as k[t+1] will be out of bounds if t = nums-1
或者在移动数字之前 nums--
的另一种变体
nums--;
for (int t=i;t<nums;t++)
k[t]=k[t+1];
关于java - Java从数组中删除项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2832420/