在Java中,如果你想要对二维数组的相邻元素进行相加,你可以使用嵌套循环来实现。以下是一个示例代码,展示了如何对两个二维数组进行相邻元素相加:
```java
public class ArrayAddition {
public static void main(String[] args) {
int[][] array1 = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
int[][] array2 = {{9, 8, 7}, {6, 5, 4}, {3, 2, 1}};
int[][] result = add(array1, array2);
// 打印结果
for (int i = 0; i < result.length; i++) {
for (int j = 0; j < result[i].length; j++) {
System.out.print(result[i][j] + "\t");
}
System.out.println();
}
}
public static int[][] add(int[][] a, int[][] b) {
int rows = a.length;
int cols = a.length;
int[][] result = new int[rows][cols];
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
result[i][j] = a[i][j] + b[i][j];
}
}
return result;
}
}
在这个例子中,`add` 方法接受两个二维数组 `a` 和 `b` 作为参数,并返回一个新的二维数组,其中每个元素是 `a` 和 `b` 中对应位置元素的和。主方法 `main` 创建了两个示例数组,并调用了 `add` 方法来计算它们的和,然后打印出结果。
请注意,这个例子假设两个输入数组的大小是相同的。如果数组的大小不同,你需要添加额外的检查来确保它们可以相加。