在 Java 中,二维数组的赋值有多种方法。以下是一些常见的方法:
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 * j;
}
}
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] = someFunction(i, j);
}
}
private int someFunction(int i, int j) {
// 根据 i 和 j 计算值并返回
return i + j;
}
import java.util.stream.IntStream;
int[][] matrix = new int[3][4];
IntStream.range(0, matrix.length).forEach(i ->
IntStream.range(0, matrix[i].length).forEach(j -> matrix[i][j] = i * j)
);
int[][] matrix = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
for (int i = 0; i < matrix.length; i++) {
for (int j = i + 1; j < matrix[i].length; j++) {
int temp = matrix[i][j];
matrix[i][j] = matrix[j][i];
matrix[j][i] = temp;
}
}
这些方法可以根据实际需求进行选择。