Scanner scanner = new Scanner(System.in);
System.out.print("Enter number of rows/columns in matrix : "); //rows and columns in matrix must be same.
int rows = scanner.nextInt();
int columns = rows;
int[][] matrix = new int[rows][rows];
System.out.println("Enter the elements in matrix :");
for (int i = 0; i < rows; i++) {
for (int j = 0; j < columns; j++) {
matrix[i][j] = scanner.nextInt();
}
}
只需添加一个sum
变量,将两个D数组中的元素相加,如下所示:
int sum = 0;
for (int i = 0; i < rows; i++) {
for (int j = 0; j < columns; j++) {
matrix[i][j] = scanner.nextInt();
sum += matrix[i][j];
}
}
System.out.print("The sum is :");
System.out.println(sum); //Simply for clarity
Java8
long sum = Arrays.stream(matrix).flatMapToInt(arr -> Arrays.stream(arr)).sum();