我怎样才能找到多维数组的和,使用户在多维数组中输入行和列

  • 本文关键字:数组 用户 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();
    }
}

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

相关内容

  • 没有找到相关文章

最新更新