二维数组基础
声明二维数组变量并创建二维数组
int[][] martix = new int[5][5];
获取二维数组的长度
- 二维数组实际上是一个其中每个元素都是一个一维数组的数组
不规则数组
- 二维数组中的每一行本身就是一个数组
- 因此,各行的长度可以不同
- 使用语法
new int[ 5 ] [ ]
创建数组时,必须指定第一个下标,new int[ ] [ ]
是错误的
处理二维数组
int[][] martix = new int[10][10];
for(int row=0; row< martix.length; row++)
for(int column=0; column<martix[row].length; column++){
martix[row][column] = input.nextInt();
}
for(int row=0; row< martix.length; row++)
for(int column=0; column<martix[row].length; column++){
martix[row][column] = (int)(Math.random()*100);
}
for(int row=0; row< martix.length; row++)
for(int column=0; column<martix[row].length; column++){
System.out.println(martix[row][column]+" ");
}
int sum = 0;
for(int row=0; row< martix.length; row++)
for(int column=0; column<martix[row].length; column++){
sum += martix[row][column];
}
for (int column=0; column<martix[0].length; column++){
int sum = 0;
for (int row=0; row<martix.length; row++)
sum += martix[row][column];
}
int maxRow = 0;
int indexOfMaxRow = 0;
for (int column=0; column<martix[0].length; column++)
maxRow += martix[0][column];
for (int row=0; row<martix.length; row++){
int totalOfThisRow = 0;
for(int column=0; column<martix[row].length; column++)
totalOfThisRow += martix[row][column];
if(totalOfThisRow > maxRow){
maxRow = totalOfThisRow;
indexOfMaxRow = row;
}
}
将二维数组传递给方法
- 将一个二维数组传递给方法时,数组的引用传递给了方法
package chapter8;
import java.util.Scanner;
public class PassTwoDimensionalArray {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int[][] m = new int[3][4];
System.out.println("Enter " + m.length + " rows and "
+ m[0].length + " columns: ");
for (int i = 0; i < m.length; i++)
for (int j = 0; j < m[i].length; j++)
m[i][j] = input.nextInt();
System.out.println("\nSum of all elements is " + sum(m));
}
public static int sum(int[][] m) {
int total = 0;
for (int row = 0; row < m.length; row++) {
for (int column = 0; column < m[row].length; column++) {
total += m[row][column];
}
}
return total;
}
}
多维数组