二维数组
介绍
1.二维数组:也是个数组保存的 相同类型的一维元素
2.书写方式
方式一:
数组类型[][] 数组名 = new 数据类型[][] 如:
int[][] array = new int[3][4]//三行四列
方式二:如
int[][] array = new int[][]
{
{1,2,3,4},
{2,3,5,6},
{5,46,8,9}
};
代码分析:
1.定义一个二维数组,二维数组中 有3个一维数组1,2,3,4 / 2,34,234,11 / 23,44,66,44
int[][] array = new int[][]
{
{1,2,3,4},
{2,3,5,6},
{5,46,51}
};
2.遍历数组
for (int i = 0; i < array.length; i++)
{
for (int j = 0; j < array[i].length; j++)
{
System.out.print(array[i][j]);
}
System.out.println();
}
2.迷宫游戏
char[][] array = {
{'#','#','#','#','#','#','#','#','#','#'},
{'#','0',' ',' ',' ',' ','#','#',' ',' '},
{'#','#',' ','#','#','#','#','#',' ','#'},
{'#',' ',' ',' ',' ','#','#','#',' ','#'},
{'#',' ','#','#',' ','#',' ',' ',' ','#'},
{'#',' ','#','#',' ','#',' ','#','#','#'},
{'#',' ',' ',' ',' ',' ',' ','#','#','#'},
{'#','#','#','#','#','#','#','#','#','#'},
};
int x = 1;
int y = 1;
int ex = 1;
int ey = 9;
System.out.println("请输入 w a s d");
while (array[ex][ey] != '0') {
printArray(array);
Scanner scanner = new Scanner(System.in);
String string = scanner .nextLine();
switch(string){
case "w":
if (array[x - 1][y] != '#') {
array[x][y] = ' ';
x = x - 1;
array[x][y] = '0';
}
break;
case "s":
if (array[x + 1][y] != '#') {
array[x][y] = ' ';
x = x + 1;
array[x][y] = '0';
}
break;
case "a":
if (array[x][y - 1] != '#') {
array[x][y] = ' ';
y = y - 1;
array[x][y] = '0';
}
break;
case "d":
if (array[x][y + 1] != '#') {
array[x][y] = ' ';
y = y + 1;
array[x][y] = '0';
}
break;
default:
System.out.println();
break;
}}
System.out.println("恭喜过关");
}
public static void printArray(char[][] array) {
for (int i = 0; i < array.length; i++) {
for (int j = 0; j < array[i].length; j++) {
System.out.print(array[i][j]);
}
System.out.println();
}
}
}
多维数组
介绍
1.三维
2.书写如下:
int[][][] arr = new int [2][3][4];
这是2层2行3列 的三维数组 有2个二维数组 每个二维数组中有三个一维数组 每一个一维数组有4个元素
打印三维数组
int[][][] arr = new int[][][] {
{
{1,2},
{1,2},
{2,3},
},
{
{2,2,5},
{3,3,2},
{5,5,5},
}
};
int sum = 0;
for (int i = 0; i < arr.length; i++)
{
for (int j = 0; j < arr[i].length; j++)
{
for (int k = 0; k < arr[i][j].length; k++)
{
System.out.print(arr[i][j][k] + " ");
sum = sum + arr[i][j][k];
}
System.out.println();
}
System.out.println();
}
System.out.println(sum);
}