二维数组的创建

二维数组好比一个表格,第一个下标表示行,第二个下标表示列,数组的创建和初始化与一位数组一模一样,及二维数组就是一个把多个一维数组包起来的数组。
数组的创建:

type[][] arrayName;或者 type arrayName[][];

数组的初始化:

  1. 给数组分配空间大小,不能被修改,在赋值。
type[][] arrayName=new type[length1][length2]
  1. 通过new给数组赋值,不给空间大小。
type[][] arrayName=new type[][]{{1,2,3},{1,2,3}};
  1. 直接给数组赋值,空间大小不分配。
type[][] arrayName={{1,2,3},{1,2,3}};
  1. 数组的二维长度为空。
type[][] arrayName=new type[length1][];

数组元素的获取:

二维数组要通过两个下标来获取,例如:arrayName[0][0] 获取最前面的元素值,arrayName[arrayName.length-1][arrayName[arrayName.length-1].length-1] 取出数组的最后一个元素。

例1: 给定一个3行3列的二维数组,并初始化赋值,每行输出三个就换行。

public class dome2{
 	public static void main(String[] args) {
 	  int[][] a= {{1,6,5},{7,3,0},{1,5,7}};
 	  
 	  for(int i=0;i<a.length;i++) {  //二维数组的行循环
 		  
 		  for(int j=0;j<a[i].length;j++) {  //二维数组的列循环
 			  
 			 System.out.print(a[i][j]+" ");  //输出每个元素
 			 
 			  if(a[i][2]==a[i][j]) {  //当每一行输出三列后换行
 				  
 				  System.out.println();
 				  
 			  }
 		  }
 	  }
	}
}

结果
1 6 5
7 3 0
1 5 7

例2: 循环输入3行3列的二维数组,并将它顺时针旋转90°输出三行三列。

import java.util.Scanner;

public class dome2{
 	public static void main(String[] args) {
 	  int[][] a=new int[3][3];
 	  Scanner sc=new Scanner(System.in);
 	  //循环输入
 	  for(int i=0;i<a.length;i++) {
 		  for(int j=0;j<a[i].length;j++) {
 			  a[i][j]=sc.nextInt();
 		  }
 	  }
 	  //每行3个换行
 	 for(int i=0;i<a.length;i++) {
		  for(int j=0;j<a[i].length;j++) {
			  System.out.print(a[i][j]+" ");
			  if(a[i][2]==a[i][j]) {
				  System.out.println();
			  }
		  }
	  }
 	 //创建新的数组并且旋转赋值
 	 int[][] b=new int[3][3];
 	 for(int i=0;i<3;i++) {
		  for(int j=0;j<3;j++) {
			  b[j][2-i]=a[i][j];
		  }
	  }
 	 //循环输出
 	for(int i=0;i<b.length;i++) {
		  for(int j=0;j<b[i].length;j++) {
			  System.out.print(b[i][j]+" ");
			  if(b[i][2]==b[i][j]) {
				  System.out.println();
			  }
		  }
	  }
	}
}

结果
1 2 3 4 5 6 7 8 9
1 2 3
4 5 6
7 8 9
旋转后的结果
7 4 1
8 5 2
9 6 3

Logo

旨在为数千万中国开发者提供一个无缝且高效的云端环境,以支持学习、使用和贡献开源项目。

更多推荐