class Demo1_GetNewArray {
public static void main(String[] args) {
int[] array = {1,3,1,0,5,0,5,0,4,0,2,4,3,4,0,10,40,3,0};
int [] newArray = getNewArray(array);
printArray(newArray);
System.out.println();
System.out.println("除去0元素之后的新数组长度是" + newArray.length);
}
public static int[] getNewArray(int[] array){
int count = 0;
for (int i = 0;i<array.length ;i++ ) {
if (array[i]==0) {
count++;
}
}
int length = array.length - count;
int [] newArray = new int [length];
int j = 0;
for (int i = 0;i<length ;i++ ) {
while (j<array.length) {
if (array[j]!=0) {
newArray[i] = array[j];
j++;
break;
} else{
j++;
}
}
}
return newArray;
}
public static void printArray(int[] array){
for (int i = 0;i<array.length ;i++ ) {
System.out.print(array[i] + " ");
}
}
}