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();
}
}
Simply add a sum
variable which adds up the elements in the two D array like so:
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();
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.