數組的簡單練習題

1.將一個給定的整型數組轉置輸出,
例如: 源數組,1 2 3 4 5 6
轉置以後的數組,6 5 4 3 2 1java

package Array; public class arrayTest1 { public static void main(String[] args) { int[] a={1,2,3,4,5,6}; int m=a.length; int temp; for (int i = 0; i <m/2; i++) { temp=a[i]; a[i]=a[m-i-1]; a[m-i-1]=temp; } for (int i = 0; i < m; i++) { System.out.print(a[i]+" "); } } }

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} ;數組

package Array; public class arrayTest2 { 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 count=0; for (int i = 0; i <oldArr.length ; i++) { if(oldArr[i]!=0){ count++; } } int[] newArr=new int[count]; for (int i = 0,j=0; i <oldArr.length ; i++) { if(oldArr[i]!=0) { newArr[j]=oldArr[i]; j++; } } System.out.print("新數組爲:"); for (int i = 0; i < count; i++) { System.out.print(newArr[i]+" "); } } }

3.如今給出兩個數組:
數組a:"1,7,9,11,13,15,17,19"
數組b:"2,4,6,8,10"
兩個數組合併爲數組c。spa

package Array; import java.util.ArrayList; import java.util.List; public class arrayTest3 { public static void main(String[] args) { int[] a = {1, 7, 9, 11, 13, 15, 17, 19}; int[] b = {2, 4, 6, 8, 10}; int m = a.length + b.length; int j = 0,temp; int[] c = new int[m]; for (int i = 0; i < a.length; i++) { c[i] = a[i]; } for (int i = a.length; i < m; i++) { c[i] = b[j]; j++; } for(int i=0;i<m-1;i++){ for(int s=0;s<m-1-i;s++){ if(c[s]>c[s+1]){ temp=c[s]; c[s]=c[s+1]; c[s+1]=temp; } } } for (int i = 0; i < m; i++) { System.out.print(c[i] + " "); } } }
相關文章
相關標籤/搜索