java 实现二维数组按行列求和
时间: 2023-12-20 12:57:51 浏览: 151
java二维数组
以下是Java代码示例,实现对二维数组按行列求和:
```
public class SumOf2DArray {
public static void main(String[] args) {
int[][] arr = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
int row = arr.length;
int col = arr[0].length;
int[] rowSum = new int[row];
int[] colSum = new int[col];
// 按行求和
for (int i = 0; i < row; i++) {
int sum = 0;
for (int j = 0; j < col; j++) {
sum += arr[i][j];
}
rowSum[i] = sum;
}
System.out.println("按行求和结果:");
for (int i = 0; i < row; i++) {
System.out.print(rowSum[i] + " ");
}
System.out.println();
// 按列求和
for (int j = 0; j < col; j++) {
int sum = 0;
for (int i = 0; i < row; i++) {
sum += arr[i][j];
}
colSum[j] = sum;
}
System.out.println("按列求和结果:");
for (int j = 0; j < col; j++) {
System.out.print(colSum[j] + " ");
}
}
}
```
输出:
```
按行求和结果:
6 15 24
按列求和结果:
12 15 18
```
阅读全文