Given a two-dimensional array, calculate the sum of all its elements。用Java编写
时间: 2024-05-06 11:18:16 浏览: 128
Molecular cancer classification using ameta-sample-based regularized robust coding method
可以使用双重循环遍历二维数组,并将每个元素的值相加,最终得到总和。以下是Java代码示例:
```java
public class TwoDimensionalArraySum {
public static void main(String[] args) {
int[][] arr = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
int sum = 0;
for (int i = 0; i < arr.length; i++) {
for (int j = 0; j < arr[i].length; j++) {
sum += arr[i][j];
}
}
System.out.println("The sum of all elements in the array is: " + sum);
}
}
```
输出结果为:
```
The sum of all elements in the array is: 45
```
阅读全文