brief introduction
One-dimensional arrays can store linear sets of elements, while two-dimensional arrays can store matrices and tables.
Basic knowledge of two-dimensional arrays
Elements of a two-dimensional array are accessed by the subscripts of rows and columns.
Declare two-dimensional array variables and create two-dimensional arrays
The syntax for declaring two-dimensional arrays is as follows:
Data type [][] array name; perhaps Data type array name [][];
For example:
int[][] matrix; perhaps int matirx[][]; Use this grammar to create an int-type two-dimensional array of 5 x 5: matrix = new int[5][5];
Two subscripts are used in two-dimensional arrays, one for rows and one for columns. Like one-dimensional arrays, each subscript index value is int, starting at 0.
Note: Using matrix[2,1] to access elements with row subscripts of 2 and column subscripts of 1 is a Yangtze River error. In Java, each subscript must be placed in a pair of square brackets.
Array initialization can also be used to declare, create, and initialize a two-dimensional array:
int[][] array = {{1, 2, 3}, {2, 3, 4}, {3, 4, 5}};
Getting the Length of a Two-Dimensional Array
A two-dimensional array is actually an array, and each element of it is a one-dimensional array. The length of the array x is the number of elements in the array, which can be obtained by x.length.
Sawtooth array
Each row of a two-dimensional array red is itself an array, so the length of each row can be different. Such arrays are called sawtooth arrays.
int[][] triangleArray = {
{1, 2, 3, 4},
{2, 4, 6},
{3, 5}
};
Processing two-dimensional arrays
Nested for loops are often used to process two-dimensional arrays.
Assume that the array matrix is created as follows:
int[][] matrix = new int[10][10];
Initialization of two-dimensional arrays with input values
Using loops, the user input value initialization array is realized:
Scanner input = new Scanner(System.in);
System.out.println("Enter " + matrix.length + " rows and " + matrix[0].length + " coulmns: ");
for(int row = 0; row < matrix.length; row++) {
for(int column = 0; column < matrix[row].length; column++) {
matrix[row][column] = input.nextInt();
}
}
Initialization of two-dimensional arrays with random values
Initialize arrays using random integers between 0 and 99:
for(int row = 0; row < matrix.length; row++) {
for(int column = 0; column < matrix[row].length; column++) {
matrix[row][column] = (int)(Math.random() * 100);
}
}
Print two-dimensional arrays
To print a two-dimensional array, you can use this loop to print each element in the array:
for(int row = 0; row < matrix.length; row++) {
for(int column = 0; column < matrix[row].length; column++) {
System.out.println(matrix[row][column] + " ");
}
System.out.println();
}
Find the sum of all elements
int total = 0;
for(int row = 0; row < matrix.length; row++) {
for(int column = 0; column < matrix[row].length; column++) {
total += matrix[row][column];
}
}
Sum arrays by column
for(int column = 0; column < matrix[0].length; column++) {
int total = 0;
for(int row = 0; row < matrix.length; row++)
total += matrix[row][column];
System.out.println("Sum for column " + column + " is " + total);
}
Finding the Maximum Line Sum of Two-Dimensional Array
Use variables maxRow and indexOfMaxRow to track the maximum sum and the index value of the row, respectively.
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);
}
Random disruption
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;
}
}
Example Exercise: Sudoku
public class CheckSudokuSolution {
public static void main(String[] args) {
//Call readASolution() to read the Sudoku table
int[][] grid = readASolution();
System.out.println(isValid(grid) ? " Valid solution" : " Invalid solution ");
}
//Read user input answers from the console
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;
}
//Check if the answer is valid
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) {
//Check whether grid[i][j] is unique in line i?
for(int column = 0; column < 9; column++)
if(column != j && grid[i][column] == grid[i][j])
return false;
//Check whether grid[i][j] is unique in column J
for(int row = 0; row < 9; row++)
if(row != i && grid[row][j] == grid[i][j])
return false;
//Check whether grid[i][j] is unique in 3 x 3 lattices
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;
}
}
Multidimensional Array
A two-dimensional array consists of an array of one-dimensional arrays, while a three-dimensional array can be considered to consist of an array of two-dimensional arrays.
The declaration of two-dimensional array variables and the method of creating two-dimensional arrays can be generalized to declare n-dimensional array variables >= 3 and create n-dimensional arrays.
The following syntax declares a three-dimensional array variable scores:
double[][][] scores = new double [6][5][2];
Case Study: Daily Temperature and Humidity
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(Sytem.in);
for(int k = 0; k < NUMBER_OF_DAYS * NUMBER_OF_HOURS; k++) {
int day = input.nextint();
int hour = input.nextInt();
double temperature = input.nextDouble();
double humidity = input.nextDouble();
data[day - 1][hour - 1][0] = temperature;
data[day - 1][hour - 1][1] = humidity;
}
for(int i = 0; i < NUMBER_OF_DAYS; i++) {
double dailyTemperatureTotal = 0;
double 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);
}
}
}