去掉数组中值为0的元素,并返回一个新的数组
package com.cyl.day05;
/**
* 现在有如下的一个数组:
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}
* @author CLY
*
*/
public class DeleteZore {
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 = new int[oldArr.length-count(oldArr)];
int j=0;
for(int i=0;i<oldArr.length;i++) {
if(oldArr[i]!=0) {
newArr[j++]=oldArr[i];
}
}
printArray(newArr);
}
public static int count(int[] a) {
int count = 0;
for(int i=0;i<a.length;i++) {
if(a[i] == 0) {
count++;
}
}
return count;
}
public static void printArray(int[] arr) {
for(int i:arr) {
System.out.print(i + " ");
}
}
}