代码:
package com;
import java.util.Arrays;
public class MatrixAddition {
public static void main(String[] args) {
matrixElementSumTest();
matrixAdditionTest();
}// of main
/**
* Sum the elements of a matrix.
* @param paraMatrix The given matrix.
* @return The sum of all its elements;
*/
public static int matrixElementSum(int[][] paraMatrix) {
int resultSum = 0;
for (int i = 0; i < paraMatrix.length; i++) {
for (int j = 0; j < paraMatrix[0].length; j++){
resultSum += paraMatrix[i][j];
}//of for j
}//of for i
return resultSum;
}// of matrixElementSum
/**
* Unit test for respective method
*/
public static void matrixElementSumTest() {
int[][] tempMatrix = new int[3][4];
for (int i = 0; i < tempMatrix.length; i++) {
for (int j = 0; j<tempMatrix[0].length; j++) {
tempMatrix[i][j] = i * 10 + j;
}// of for j
}// of for i
System.out.println("The matrix is: \r\n" + Arrays.deepToString(tempMatrix));//deepToString返回指定数组“深层内容”的字符串表示形式
System.out.println("The matrix element sum is: " + matrixElementSum(tempMatrix));
}// of matrixElementSumTest
/**
* Add two matrices. Attention: NO error check is provided at this moment.
*
* @param paraMatrix1 The first matrix.
* @param paraMatrix2 The second matrix. It should have the same size as the first one
* @return The addition of these matrices
*/
public static int[][] matrixAddition(int[][] paraMatrix1, int[][] paraMatrix2) {
int[][] resultMatrix = new int[paraMatrix1.length][paraMatrix1[0].length];
for (int i = 0; i < paraMatrix1.length; i++) {
for (int j= 0; j < paraMatrix1[0].length; j++) {
resultMatrix[i][j] = paraMatrix1[i][j] + paraMatrix2[i][j];
}//of for j
}// of for i
return resultMatrix;
}// of matrixAddition
/**
* Unit test for respective method.
*/
public static void matrixAdditionTest() {
int[][] tempMatrix = new int[3][4];
for (int i = 0; i < tempMatrix.length; i++) {
for(int j = 0; j < tempMatrix[0].length; j++){
tempMatrix[i][j] = i * 10 + j;
}// of for j
}// of for i
System.out.println("The matrix is: \r\n" + Arrays.deepToString(tempMatrix));
int[][] tempNewMatrix = matrixAddition(tempMatrix,tempMatrix);
System.out.println("The new matrix is: \r\n" + Arrays.deepToString(tempNewMatrix));
}// of matrixAdditionTest
}// of class MatrixAddition
运行结果:
The matrix is:
[[0, 1, 2, 3], [10, 11, 12, 13], [20, 21, 22, 23]]
The matrix element sum is: 138
The matrix is:
[[0, 1, 2, 3], [10, 11, 12, 13], [20, 21, 22, 23]]
The new matrix is:
[[0, 2, 4, 6], [20, 22, 24, 26], [40, 42, 44, 46]]