求一个3*3矩阵对角线元素之和

题目:求一个3*3矩阵对角线元素之和 
        0 1 2 
        0 1 2 
        0 1 2

public class Test{
    public int cal(int[][] a){
        int result=0;
        for(int i=0;i<3;i++){
            for(int j=0;j<3;j++){
                if(i==j||i+j==2)
                result+=a[i][j];
            }
        }
        return result;
    }
    public static void main(String args[]){
        int[][] a = new int[3][3];
        //随便对这个矩阵赋值
        for(int i=0;i<3;i++){
            for(int j=0;j<3;j++){
                System.out.print((i+j)+" ");
                a[i][j]=i+j;
            }
            System.out.println();
        }
        System.out.println("result is: "+new Test().cal(a));    
    }
}
    /*---运行输出---
    C:\>java Test
    0 1 2
    1 2 3
    2 3 4
    result is: 10
    */
原文地址:https://www.cnblogs.com/laoquans/p/2963360.html