如何找到多维数组的总和,使用户在多维数组中输入行和列

时间:2016-08-09 04:50:22

标签: java arrays multidimensional-array

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();
    }
}

2 个答案:

答案 0 :(得分:0)

只需添加一个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

答案 1 :(得分:0)

在Java8中

long sum = Arrays.stream(matrix).flatMapToInt(arr -> Arrays.stream(arr)).sum();