08-多维数组
8.1 引言
表或矩阵中的数据可以表示为二维数组。
-
8.2 二维数组基础
二维数组中的元素通过行和列的下标来访问。- 8.2.1 声明二维数组变量并创建二维数组
- 下面是声明二维数组的语法:
数据类型 [][] 数组名; //或者 数据类型 数组名[][];//允许这种方式,但并不推荐使用它。
- 使用matrix[2,1]访问行下标为2、列下标为1的元素是一种常见的错误。在Java中,每个下摆哦必须放在一对方括号中。
- 下面是声明二维数组的语法:
- 8.2.2 获取二维数组的长度
- 二维数组实际上是一个其中每一个元素都是一个一维数组的数组。
- x.length表示的是在二维数组中有几个一维数组。x[0].length表示的是这个一维数组的长度。
- 8.2.3 不规则数组
- 二维数组中的每一行本身就是一个数组,所以各行的长度就可以不同。这样的数组称作不规则数组。
- 使用语法new int[5][]创建数组时,必须指定第一个下标。语法new int[][]是错误的。
- 8.2.1 声明二维数组变量并创建二维数组
-
8.3 处理二维数组
- 1、使用输入值初始化数组
int[][] matrix = new int[10][10]; Scanner input = new Scanner(System.in); System.out.println("Enter " + matrix.length + " rows and " + matrix[0].length + " columns: "); for (int row = 0;row < matrix.length;row++) for (int column = 0;column < matrix[row].length;column++) matrix[row][column] = input.nextInt();
- 2、使用随机值初始化数组
int[][] matrix = new int[10][10]; for (int row = 0;row < matrix.length;row++) for (int column = 0;column < matrix[row].length;column++) matrix[row][column] = (int)(Math.random() * 100);
- 3、打印数组
int[][] matrix = new int[10][10]; for (int row = 0;row < matrix.length;row++){ for (int column = 0;column < matrix[row].length;column++) System.out.print(matrix[row][column] + " "); System.out.println(); }
- 4、对所有元素求和
int[][] matrix = new int[10][10]; int total = 0; for (int row = 0; row < matrix.length; row++) for (int column = 0; column < matrix[row].length; column++) total += matrix[row][column];
- 5、按列求和
int[][] matrix = new int[10][10]; for (int column = 0;column < matrix.length;column++){ int total = 0; for (int row = 0;row < matrix[column].length;row++) total += matrix[row][column]; System.out.println("Sum for column " + column + " is " + total); }
- 6、哪一行的和最大
int[][] matrix = new int[10][10]; int maxRow = 0; int indexOfMaxRow = 0; for (int column = 0;column < matrix[0].length;column++) maxRow += matrix[0][column]; for (int row = 1;row < matrix.length;row++){ int totalOfThisRow = 0; for (int column = 0;column < matrix[row].length;column++) totalOfThisRow += matrix[row][column]; if (totalOfThisRow > maxRow){ maxRow = totalOfThisRow; indexOfMaxRow = row; } } System.out.println("Row " + indexOfMaxRow + " has the maximum sum of " + maxRow);
- 7、随机打乱
int[][] matrix = new int[10][10]; for (int i = 0;i < matrix.length;i++){ for (int j = 0;j < matrix[i].length;j++){ int i1 = (int)(Math.random() * matrix.length); int j1 = (int)(Math.random() * matrix[i].length); int temp = matrix[i][j]; matrix[i][j] = matrix[i1][j1]; matrix[i1][j1]= temp; } }
- 1、使用输入值初始化数组
-
8.4 将二维数组传递给方法
将一个数组传递给方法时,数组的引用传递给了方法。package chapter08; import java.util.Scanner; public class PassTwoDimensionalArray { public static void main(String[] args) { int[][] m = getArray(); System.out.println("\nSum of all elements is " + sum(m)); } public static int[][] getArray(){ 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(); return 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; } }
-
8.5 示例学习:多选题测验评分
- 编写一个可以进行多选题测验评分的程序
- 学生的答案存储在一个二维数组中,正确的答案存储在一个一维数组中。程序给测验评分并显示结果。他将每个学生的答案与正确答案进行比较,统计正确答案的个数,并将其显示出来。
package chapter08; public class GradeExam { public static void main(String[] args) { char[][] answers = { {'A','B','A','C','C','D','E','E','A','D'}, {'D','B','A','B','C','A','E','E','A','D'}, {'E','D','D','A','C','B','E','E','A','D'}, {'C','B','A','E','D','C','E','E','A','D'}, {'A','B','D','C','C','D','E','E','A','D'}, {'B','B','E','C','C','D','E','E','A','D'}, {'B','B','A','C','C','D','E','E','A','D'}, {'E','B','E','C','C','D','E','E','A','D'} }; char[] keys = {'D','B','D','C','C','D','A','E','D','A'}; for (int i = 0;i < answers.length;i++){ int correctCount = 0; for (int j = 0;j < answers[i].length;j++){ if (answers[i][j] == keys[j]) correctCount++; } System.out.println("Student " + i + "'s correct count is " + correctCount); } } }
-
8.6 示例学习:找出距离最近的点对
- 假设有一个点的集合,找出距离最近的点对问题就是找到两个点,他们到彼此的距离最近。
package chapter08; import java.util.Scanner; public class FindNearestPoints { public static void main(String[] args) { Scanner input =new Scanner(System.in); System.out.print("Enter the number of points: "); int numberOfPoints = input.nextInt(); double[][] points = new double[numberOfPoints][2]; System.out.print("Enter " + numberOfPoints + " points: "); for (int i = 0;i < points.length;i++){ points[i][0] = input.nextDouble(); points[i][1] = input.nextDouble(); } int p1 = 0,p2 = 1; double shortestDistance = distance(points[p1][0],points[p1][1],points[p2][0],points[p2][1]); for (int i = 0;i < points.length;i++) for (int j = i + 1;j < points.length;j++){ double distance = distance(points[i][0],points[i][1],points[j][0],points[j][1]); if (shortestDistance > distance){ p1 = i; p2 = j; shortestDistance = distance; } } System.out.println("The closest two point are " + "(" + points[p1][0] + ", " + points[p1][1] + ") and (" + points[p2][0] + ", " + points[p2][1] + ")"); } public static double distance(double x1,double y1,double x2,double y2){ return Math.sqrt((x2 - x1) * (x2 - x1) + (y2 - y1) * (y2 - y1)); } }
- 假设有一个点的集合,找出距离最近的点对问题就是找到两个点,他们到彼此的距离最近。
-
8.7 示例学习:数独
- 要解决的问题是检验一个给定的数独解决方案是否正确。
- 1、检查是否每行都有1到9的数字以及每列都有1到9数字,并且每个小的方块都有1到9的数字。
- 2、检查每个单元格,每个单元格必须是1到9的数字,并且每个单元格数字在每行、每列以及每个小方盒中都是唯一的。
package chapter08; import java.util.Scanner; public class CheckSudokuSolution { public static void main(String[] args) { int[][] grid = readASolution(); System.out.println(isValid(grid) ? "Valid solution" : "Invalid solution"); } public static int[][] readASolution(){ Scanner input = new Scanner(System.in); System.out.println("Enter a Sudoku puzzle solution:"); int[][] grid = new int[9][9]; for (int i = 0;i < 9;i++) for (int j = 0;j < 9;j++) grid[i][j] = input.nextInt(); return grid; } public static boolean isValid(int[][] grid){ for (int i = 0;i < 9;i++) for (int j = 0;j < 9;j++) if (grid[i][j] < 1 || grid[i][j] > 9 || !isValid(i,j,grid)) return false; return true; } public static boolean isValid(int i,int j,int[][] grid){ for (int column = 0;column < 9;column++) if (column != j && grid[i][column] == grid[i][j]) return false; for (int row = 0;row < 9;row++) if (row != i && grid[row][j] == grid[i][j]) return false; for (int row = (i / 3) *3;row < (i / 3) * 3 + 3;row++) for (int col = (j / 3) * 3;col < (j / 3) * 3 + 3;col++) if (!(row == i && col == j) && grid[row][col] == grid[i][j]) return false; return true; } }
- 要解决的问题是检验一个给定的数独解决方案是否正确。
-
8.8 多维数组
二维数组由一个一维数组的数组组成,而一个三维数组可以认为是由一个二维数组的数组所组成。- 8.8.1 示例学习:每日温度和湿度
- 假设气象站每天每小时都会记录湿度和温度,并且将过去十天的数据都存储在一个名为Weather.txt的文本文件中。文件中的每一行包含四个数字,分别表明天、小时、温度和湿度。你的任务是编写程序,静思园10天的日均温度和日均湿度。可以使用输入重定向来读取文件。
package chapter08; import java.util.Scanner; public class Weather { public static void main(String[] args) { final int NUMBER_OF_DAYS = 10; final int NUMBER_OF_HOURS = 24; double[][][] data = new double[NUMBER_OF_DAYS][NUMBER_OF_HOURS][2]; Scanner input = new Scanner(System.in); for (int k = 0;k < NUMBER_OF_DAYS * NUMBER_OF_HOURS;k++){ int day = input.nextInt(); int hours =input.nextInt(); double temperature = input.nextDouble(); double humidity = input.nextDouble(); data[day - 1][hours - 1][0] = temperature; data[day - 1][hours - 1][1] = humidity; } for (int i = 0;i < NUMBER_OF_DAYS;i++){ double dailyTemperatureTotal = 0,dailyHumidityTotal = 0; for (int j = 0;j < NUMBER_OF_HOURS;j++){ dailyTemperatureTotal += data[i][j][0]; dailyHumidityTotal += data[i][j][1]; } System.out.println("Day " + i + "'s average temperature is " + dailyTemperatureTotal / NUMBER_OF_HOURS); System.out.println("Day " + i + "'s average humidity is " + dailyHumidityTotal / NUMBER_OF_HOURS); } } }
- 可以使用下面的命令来运行这个程序:
java Weather < Weather.txt
- 假设气象站每天每小时都会记录湿度和温度,并且将过去十天的数据都存储在一个名为Weather.txt的文本文件中。文件中的每一行包含四个数字,分别表明天、小时、温度和湿度。你的任务是编写程序,静思园10天的日均温度和日均湿度。可以使用输入重定向来读取文件。
- 8.8.2 示例学习:猜生日
package chapter08; import java.util.Scanner; public class GuessBirthdayUsingArray { public static void main(String[] args) { int day = 0 ; int answer; int[][][] dates = { { {1,3,5,7}, {9,11,13,15}, {17,19,21,23}, {25,27,29,31} }, { {2,3,6,7}, {10,11,14,15}, {18,19,22,23}, {26,27,30,21} }, { {4,5,6,7}, {12,13,14,15}, {20,21,22,23}, {28,29,30,31} }, { {8,9,10,11}, {12,13,14,15}, {24,25,26,27}, {28,29,30,31} }, { {16,17,18,19}, {20,21,22,23}, {24,25,26,27}, {28,29,30,31} } }; Scanner input = new Scanner(System.in); for (int i = 0;i < 5;i++){ System.out.println("Is your birthday in set " + (i + 1) + "?"); for (int j = 0;j < 4;j++){ for (int k = 0;k < 4;k++) System.out.printf("%4d",dates[i][j][k]); System.out.println(); } System.out.print("\nEnter 0 for No and 1 for Yes: "); answer = input.nextInt(); if (answer == 1) day += dates[i][0][0]; } System.out.println("Your birthday is " + day); } }
- 8.8.1 示例学习:每日温度和湿度