Day 7

7.1 矩阵的赋值。

数组声明:dataType[ ] name或者dataType[ ][ ] name;

创建数组:name = new dataType[size]或者name = new dataType[size][size];

7.2 二重循环。

代码:

package pracitce;

import java.util.Arrays;

public class Day7 {

	/**
	 *********************
	 * The entrance of the program.
	 * 
	 * @param args Not used now.
	 *********************
	 */
	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 i
		} // Of for j

		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));
		System.out.println("The matrix element sum is: " + matrixElementSum(tempMatrix) + "\r\n");
	}// 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's.
	 * @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 matrixAddtion

	/**
	 **************
	 * 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[][] tempNewMareix = matrixAddition(tempMatrix, tempMatrix);
		System.out.println("The new matrix is: \r\n" + Arrays.deepToString(tempNewMareix));
	}// Of matrixAdditionTest
}// Of class Day7

结果:

Day 7_第1张图片

 7.3 疑问

"\r" 回车符和 "\n" 换行符单独使用效果都一样,但是为什么要同时写 "\r\n" ?

为什么 "\r\n" 和 "\n\r" 效果不同?

你可能感兴趣的:(java)