/* 去掉數組中的0元素 */ public class TestFour{ 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 length=0;//獲取新數組的長度 for(int num:oldArr) { if(num!=0) length++; } int []newArray=new int[length]; //以下是此程序的精妙之處 int size=0; for(int n:oldArr) { if(n!=0) { newArray[size++]=n; } } for(int n:newArray) { System.out.println(n); } } }
此程序的精妙之處在於:結合增強式for循環,給新數組賦值。。。。。。
以下是我第一次寫的此題的循環
/* 4.合併數組操作: 現有如下一個數組: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} */ public class TogetherArray{ public static void main(String[]args) { int arrayLength=0; int oldArr[]={1,3,4,5,0,0,6,6,0,5,4,7,6,7,0,5}; System.out.println("合併前的數組:"); for(int i=0;i<oldArr.length;i++) { System.out.println(oldArr[i]); } //實現數組的合併 togetherArr(oldArr); } //實現數組的合併 public static void togetherArr(int []b) { int m = 0;//實現賦值計數 int n = b.length;//計數newArr的長度 int i = 0; for(i=0;i<b.length;i++) { if(b[i]==0) n--; } //創建新函數接收大於零的數 int[] c=new int[n]; //實現賦值 for(i=0;i<b.length;i++) { if(b[i]!=0) { c[m]=b[i]; m++; } } System.out.println("合併後的數組"); for(m=0;m<c.length;m++) { System.out.println(c[m]); } } }