去掉一个数组中值为0的元素,并返回一个新的数组

去掉数组中值为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;

        //将不是0的元素赋予到新数组中
        for(int i=0;i<oldArr.length;i++) {
            if(oldArr[i]!=0) {
                newArr[j++]=oldArr[i];
            }
        }
        //调用打印数组的方法
        printArray(newArr);

    }



    //判断数组中0的个数
    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 + "  ");
        }
    }

}

猜你喜欢

转载自blog.csdn.net/qq_42846655/article/details/81454591