将数组中值为0的项去掉,将不为0的值存入一个新的数组,生成新数组

package com.zhidi.zuoye;


public class Zuoye02 {


public static void main(String[] args) {
// 现在有如下的一个数组:
// 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} ;


int[] oldArr = {1,3,4,5,0,0,6,6,0,5,4,7,6,7,0,5};

int len = 0;
System.out.println("老数组");
for (int i = 0; i < oldArr.length; i++) {
System.out.print(oldArr[i]+"  ");
if(oldArr[i] != 0){
len ++;
}
}

int[] newArr = new int[len];

int a = 0;
for (int i = 0; i < oldArr.length; i++) {
if(oldArr[i] != 0){
newArr[a] = oldArr[i];
a++;
}
}

System.out.println("\n新数组");
for (int i = 0; i < newArr.length; i++) {
System.out.print(newArr[i]+"  ");
}


}


}

你可能感兴趣的:(案例,数组)