数组
数组创建必须有长度
数组创建的主流两种方法:
- dataType[] arrayRefVar=new dataType[arraySize]; 实例:int[] a=new int[20];
- dataType[] arrayRefVar={value1,value2,value3,……,valuek} 实例:int[] a={1,2,3,4,5,6}
1.将一个给定的整型数组转置输出,
例如: 源数组,1 2 3 4 5 6
例如: 源数组,1 2 3 4 5 6
转置之后的数组,6 5 4 3 2 1
方法一:
1 public class Text1 { 2 public static void main(String[] args) { 3 int[] a={1,2,3,4,5,6}; 4 int x; 5 for (int i=0,j=5;i<3;i++,j--){ 6 x=a[i]; 7 a[i]=a[j]; 8 a[j]=x; 9 } 10 for (int z:a){ 11 System.out.print(z+" "); 12 } 13 } 14 }
方法二:
1 public class Text1 { 2 public static void main(String[] args) { 3 int[] a={1,2,3,4,5,6}; 4 int[] b=new int[6]; 5 for (int i=0,j=a.length-1; i <a.length ; i++,j--) { 6 b[i]=a[j]; 7 } 8 for (int z:b){ 9 System.out.print(z+" "); 10 } 11 } 12 }
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} ;
1 public class Text2 { 2 public static void main(String[] args) { 3 int[] oldArr={1,3,4,5,0,0,0,5,4,7,6,7,0,5}; 4 int num = 0; 5 for (int x:oldArr) { 6 if (x !=0) 7 num++; 8 } 9 int[] newArr=new int[num]; 10 11 for (int i=0,j=0;i<oldArr.length;i++) 12 { 13 if (oldArr[i]!=0){ 14 newArr[j]=oldArr[i]; 15 j++; 16 } 17 } 18 for (int x:newArr) 19 { 20 System.out.print(x+" "); 21 } 22 } 23 }
3.现在给出两个数组:
数组a:"1,7,9,11,13,15,17,19"
数组b:"2,4,6,8,10"
数组a:"1,7,9,11,13,15,17,19"
数组b:"2,4,6,8,10"
两个数组合并为数组c。
1 public class Text3 { 2 public static void main(String[] args) { 3 int[] a={1,7,9,11,13,15,17,19}; 4 int[] b={2,4,6,8,10}; 5 int size=a.length+b.length; 6 int[] c=new int[size]; 7 for (int i = 0; i <size ; i++) { 8 if (i<a.length){ 9 c[i]=a[i]; 10 } 11 if (i>=a.length) { 12 c[i]=b[i-a.length]; 13 } 14 } 15 for (int x:c) { 16 System.out.print(x+" "); 17 } 18 } 19 }
浙公网安备 33010602011771号