第八章:多維數組
一.多維數組的基礎知識
1.語法
數據類型[][] 數組名;
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}};
二維數組更像是一個大的一維數組,數組的每個元素又是一個一維數組
x[0].length=x[1].length=x[3].length=4
聲明一個三維數組:int[][][] array=new int[6][5][4];
每個三維數組中的每個元素爲一個二維數組,每個二維數組中的元素是一個一維數組。
二.創建鋸齒數組
1.語法
int[][] array=new int[3][];必須指定第一個下標
下面例子是創建一個隨機由0和1組成的鋸齒數組並打印
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();//換行
}
}
結果:
三.經典回顧
1.使用方法頭
public static double[][] multiolyMatrix(double[][] a,double[][] b)
計算兩個3*3矩陣的乘積
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();
}
結果爲:
四.總結
通過對本章的學習,我學到了定義多維數組,創建鋸齒數組,以及對多維數組更深層次的理解,通過經典回顧,我鞏固了對多維數組的使用。
加油!第九章待更……