移除数组中不为0的项
*现在有如下的一个数组: int oldArr[]=现在有如下的一个数组:
* int oldArr[]={1,3,4,5,0,0,6,6,0,5,4,7,6,7,0,5} ;
要求将以上数组中值为0的项去掉,将不为0的值存入一个新的数组,生成的新数组为:
int newArr[]={1,3,4,5,6,6,5,4,7,6,7,5} ;
public static void main(String[] args) {
int oldArr[] = {1,3,4,5,0,0,6,6,0,5,4,7,6,7,0,5};
int [] newArr = removeZeroFromArray(oldArr);
System.out.println(Arrays.toString(newArr));
}
public static int [] removeZeroFromArray(int[]arr) {
//统计原数组中非0的个数
int length = 0;
for (int i = 0; i < arr.length; i++) {
if (arr[i]!=0) {
length ++;
}
}
int[]newArr = new int [length];
int index = 0;
for (int i = 0; i < arr.length; i++) {
if (arr[i]!=0) {
newArr[index] = arr[i];
index++;
}
}
return newArr;
}