在 Java 中,二維數(shù)組的賦值有多種方法。以下是一些常見的方法:
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;
}
}
這些方法可以根據實際需求進行選擇。