数组_2

问题:
    现在有如下的一个数组:
        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} ;

思路(个人):定义一个数组oldArr,数组元素已确定,对数组oldArr进行循环遍历并定义一个变量j统计不是0的元素个数,使用if语句判断,如果是数组中元素为0,则使用continue语句跳过此次循环,否则j+1;遍历完毕后,得到新数组的长度j,定义新数组,再次使用for循环遍历数组,将老数组中元素与0进行比较,如果等0,使用continue跳过此次循环,否则,将老数组元素赋值给新数组元素。

源码:

public class Test02 {
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 j=0;
for (int i=0;i<16;i++)
{
if(oldArr[i]==0)
{
continue;
}
j++;
}
int[] newArr = new int[j];
int n = 0;
for(int m=0;m<16;m++)
{
if (oldArr[m]==0)
{
continue;
}else {
newArr[n] =oldArr[m];
n++;
}
}
for (int i=0;i<j;i++)
{
System.out.print(newArr[i]+" ");
}

}
}
输出结果:

 

posted @ 2019-04-23 10:00  友人Y  阅读(174)  评论(0编辑  收藏  举报