去除數組中爲零的項

package exercise;
/*
 * 去除數組中爲零的項*/
public class Demo2 {
    public static void main(String[] args) {
        int oldArray[] = new int[]{1,2,3,4,0,0,0,0,0,5,6,0,7,0,8,0,9};
        int newArray[] = new int[count(oldArray)];
        copy(oldArray,newArray);
        print(newArray);
    }
    
    public static int count(int temp[]){
        int n = 0;
        for(int x = 0; x < temp.length ; x++ ){
            if(temp[x]!=0){
                n++;
            }
        }
        return n;
    }
    
    public static void copy(int old[],int ne[]){
        int n = 0;
        for(int x = 0;x < old.length; x++){
            if(old[x] != 0){
                ne[n] = old[x];
                n++;
            }
        }
    }

    public static void print(int temp[]){
        for(int i=0; i< temp.length;i++){
            System.out.print(temp[i]+"、");
        }
        System.out.println();
    }
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章