1 import java.util.Scanner;
2 /**
3 * @author 冰樱梦
4 * 时间:2018年12月
5 * 题目:求矩阵主对角线元素的和
6 *
7 */
8 public class Exercise08_02 {
9 public static void main(String[] args){
10 Scanner input=new Scanner(System.in);
11 System.out.println("Enter the arrays row: ");
12 int row=input.nextInt();
13 System.out.println("Enter the arrays column: ");
14 int col=input.nextInt();
15 double[][] list=new double[row][col];
16 for(int i=0;i<list.length;i++){
17 for(int j=0;j<list[i].length;j++){
18 list[i][j]=input.nextDouble();
19 }
20 }
21 System.out.println("Sum of the elements in the major diagonal is "+sumMajorDiagonal(list));
22 }
23
24
25
26 /**
27 * @param m
28 * @return
29 * 返回主对角线的和
30 */
31 public static double sumMajorDiagonal(double [][] m){
32 double total=0;
33 for(int i=0;i<m.length;i++){
34 total+=m[i][i];
35 }
36 return total;
37 }
38 }