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

In Java, you can use loops to assign values to a two-dimensional array. Below is an example code:

int[][] arr = new int[3][3]; // 创建一个3x3的二维数组

for (int i = 0; i < arr.length; i++) {
    for (int j = 0; j < arr[i].length; j++) {
        arr[i][j] = i + j; // 赋值为行索引和列索引之和
    }
}

In the above code, two nested loops are used to iterate over each element of a two-dimensional array. The outer loop is used to traverse rows, while the inner loop is used to traverse columns. By using the sum of the row index and column index, a value can be assigned to each element.

In this example, the array is assigned the following values:

arr[0][0] = 0
arr[0][1] = 1
arr[0][2] = 2
arr[1][0] = 1
arr[1][1] = 2
arr[1][2] = 3
arr[2][0] = 2
arr[2][1] = 3
arr[2][2] = 4

You can assign values to a two-dimensional array based on your actual needs in a similar way.

bannerAds