Chapter 8: Multidimensional Array
1. Basic knowledge of multidimensional array
1. Syntax
data type [][] array name;
int[][] array=new int[3][4];
array[0][0]=1;
……
int[][] array= {
{
2,3},{
5,6},{
7,8}};
int[][] array=new int[][]{
{
2,3},{
5,6},{
7,8}};
A two-dimensional array is more like a large one-dimensional array, and each element of the array is a one-dimensional array
x[0].length=x[1].length=x[3].length=4
Declare a three-dimensional array: int[][][] array=new int[6][5][4];
each element in each three-dimensional array is a two-dimensional array, and each element in the two-dimensional array is A one-dimensional array.
2. Create a sawtooth array
1. Syntax
int[][] array=new int[3][]; must specify the first subscript
The following example is to create a random jagged array consisting of 0 and 1 and print it
public static void main(String[] args) {
// TODO Auto-generated method stub
int[][] array = new int[3][];//创建一个锯齿数组
array[0] = new int[4];
array[1] = new int[2];
array[2] = new int[3];//定义一维数组的长度
//打印数组需要使用循环
for (int i = 0; i < array.length; i++) {
for (int j = 0; j < array[i].length; j++) {
array[i][j] = (int) (Math.random() * 2);//为锯齿数组赋值
System.out.print(array[i][j] + " ");//打印
}
System.out.println();//换行
}
}
result:
Three. Classic Review
1. Use the method header
public static double[][] multiolyMatrix(double[][] a,double[][] b) to
calculate the product of two 3*3 matrices
public static void main(String[] args) {
// TODO Auto-generated method stub
double[][] a = new double[3][3];
double[][] b = new double[3][3];
addElement(a);//向数组中添加元素
addElement(b);
double[][] c = multiolyMatrix(a, b);//乘法
printArray(a);//打印数组
System.out.println("*");
printArray(b);
System.out.println("=");
printArray(c);
}
public static void addElement(double[][] array) {
System.out.println("请输入数组元素");
Scanner in = new Scanner(System.in);
for (int i = 0; i < array.length; i++) {
for (int j = 0; j < array[i].length; j++) {
array[i][j] = in.nextDouble();
}
}
}
public static double[][] multiolyMatrix(double[][] a, double[][] b) {
double[][] c = new double[3][3];
for (int i = 0; i < a.length; i++) {
for (int j = 0; j < a[i].length; j++) {
double sum = 0;//定义一个变量接收乘积和
for (int k = 0; k < a[i].length; k++) {
sum += a[i][k] * b[k][j];
}
c[i][j] = sum;//将c[i][j]设置为sum
}
}
return c;
}
public static void printArray(double[][] array) {
for (int i = 0; i < array.length; i++) {
for (int j = 0; j < array[i].length; j++) {
System.out.printf("%.1f ", array[i][j]);
}
System.out.println();
}
System.out.println();
}
The result is:
Four. Summary
Through the study of this chapter, I learned to define multidimensional arrays, create sawtooth arrays, and have a deeper understanding of multidimensional arrays. Through classic review, I have consolidated the use of multidimensional arrays.
Come on! Chapter 9 To Be More...