一维数组
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
| int[] as = new int[]{11,12,13,14,15}; int[] bs = new int[ 5 ]; int i; for(i=0; i<as.length; i++){ bs[i] = as[i]; } for(i=0; i<as.length; i++){ System.out.print(“bs[“+i+”]=”+bs[i]+”\t”); }
int[] as = {1,2,3,4,5}; int[] bs = new int[3]; bs = Arrays.copyOf(as,as.length); for(int i=0; i<bs.length; i++){ System.out.println(bs[i]); }
|
1 2 3 4 5 6 7 8 9 10 11 12 13
| int[] ns = {11,59,2,47,68,32,555}; int i=-1;
Arrays.sort(ns);
ns[0]=0;
ns[ns.length-1]=0;
for(i=0; i<ns.length-1; i++){ System.out.print("ns["+i+"]="+ns[i]+"\t"); }
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
| int[] ns = new int[6];
Random obj = new Random();
int i=-1; int j=-1; for( i=0; i<ns.length; i++){ ns[i] = obj.nextInt(13)+1 ; for(j=0; j<=i-1; j++){ if(ns[j] == ns[i]){ i--; } } }
for(i=0; i<ns.length; i++){ System.out.print(ns[i]+"\t"); }
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49
| int[] ns = new int[7];
Random obj = new Random();
int i=-1; int j=-1; for( i=0; i<ns.length-1; i++){ ns[i] = obj.nextInt( 33 )+1 ; for( j=0; j<=i-1; j++){ if( ns[j] == ns[i]){ i--; } } }
ns[ ns.length-1 ] = obj.nextInt(16)+1;
String sysNum = ""; for(i=0; i<ns.length; i++){ sysNum = sysNum+ ns[i] +","; }
int[] us = new int[7]; Scanner input = new Scanner(System.in); System.out.print("请自选号码:"); for(i=0; i<us.length; i++){ us[i] = input.nextInt(); }
String userNum = ""; for(i=0; i<us.length; i++){ userNum = userNum + us[i] +","; }
if( sysNum.equals( userNum) ){ System.out.println("恭喜您双色球获得特等奖【1 RMB】"); }else{ System.out.println("谢谢惠顾,欢迎下次再来!"); }
|
二维数组
二维数组就是由一维数组组成的数组,其元素是一维数组。
二维数组定义时需要两个中括号,方式如下:
1 2 3 4 5 6
| 数据类型[][] 数组名 = new 数据类型[行数][列数]; int[][] arr = new int[2][3]; int[][] arr = new int[3][];
定义二维数组arr以后, arr是二维数组,arr[i]是一维数组,arr[i][j]是数据。 其中,最左边的中括号里面必须有长度。
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
| int[][] ns = new int[3][4]; int i=-1,j=-1; int num = 1; for(i=0; i<3; i++){ for(j=0; j<4; j++){ ns[i][j]=num; num++; } }
for( i=0; i<3; i++){ for(j=0; j<4; j++){ System.out.print(ns[i][j]+”\t”); } System.out.println(“”); } System.out.println(“此时num是:”+num);
|
二维数组常见算法
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29
| int[][] ns = new int[3][4]; int i=-1,j=-1; int num=1;
for( i=0; i<3; i++){ for(j=0; j<4; j++){ ns[i][j] = num++; } }
int[] sum = new int[3];
for(i=0; i<3; i++){ for(j=0; j<4; j++){ sum[i] += ns[i][j]; } } System.out.println("第1行数字和:"+ sum[0]); System.out.println("第2行数字和:"+ sum[1]); System.out.println("第3行数字和:"+ sum[2]);
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
| int[][] ns = new int[3][4]; int i=-1,j=-1; int num=1;
for( i=0; i<3; i++){ for(j=0; j<4; j++){ ns[i][j] = num++; } }
int[] sum = new int[4];
for(i=0; i<4; i++){ for(j=0; j<3; j++){ sum[i] += ns[j][i] ; } } for(i=0; i<4; i++){ System.out.println("第"+(i+1)+"列数字和:"+ sum[i]); }
|