How to create a two-dimensional array and assign values in Java?

In Java, you can create and assign values to a two-dimensional array using the following methods:

int[][] matrix = new int[rowCount][columnCount];

// 给二维数组赋值
matrix[rowIndex][columnIndex] = value;

rowCount and columnCount refer to the number of rows and columns in a two-dimensional array. While rowIndex and columnIndex indicate the position of the element to be assigned within the two-dimensional array, the value refers to the value to be assigned to that element.

For example, create a 3 by 4 two-dimensional array and assign values to its elements.

int[][] matrix = new int[3][4];

matrix[0][0] = 1;
matrix[0][1] = 2;
matrix[0][2] = 3;
matrix[0][3] = 4;

matrix[1][0] = 5;
matrix[1][1] = 6;
matrix[1][2] = 7;
matrix[1][3] = 8;

matrix[2][0] = 9;
matrix[2][1] = 10;
matrix[2][2] = 11;
matrix[2][3] = 12;

You can also use loops to assign values to a two-dimensional array.

int[][] matrix = new int[3][4];

for (int i = 0; i < matrix.length; i++) {
    for (int j = 0; j < matrix[i].length; j++) {
        matrix[i][j] = i * matrix[i].length + j + 1;
    }
}

The above code uses two loops to iterate through each element of a two-dimensional array, and calculates the value to be assigned based on the row and column indices.

bannerAds