求矩阵的主对角线之和

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Scanner;
public class Triangle{
public static void main(String[] args)throws IOException{
int n=0;
System.out.print("enter matrix's dimension and content:");
Scanner reader=new Scanner(System.in);
n=reader.nextInt(); //n is the size of the matrix

String[] s=new String[n];
Scanner[] scan=new Scanner[n];
long[][] a=new long[n][n];
long sum=0;
BufferedReader stdin=new BufferedReader(new InputStreamReader(System.in));//BufferedReader包装字符流,将其存入缓存,可提高读的效率
for(int i=0;i<n;i++){
s[i]=stdin.readLine();
}
System.out.println("your matrix:");
for(int i=0;i<n;i++)
{
scan[i]=new Scanner(s[i]);//enter the marix number to scan[i]
}
for(int i=0;i<n;i++)
{
for(int j=0;j<n;j++)
{
a[i][j]=scan[i].nextLong();//save the matrix number to a[][]
}
}
for(int i=0;i<n;i++)
{
for(int j=0;j<n;j++)
{
if(i==j)
{
sum=sum+a[i][j];
}
System.out.print(a[i][j]+" ");
}
System.out.println("");

}
System.out.println("matrix's sum of the main diagonal:"+sum);
}
}

原文地址:https://www.cnblogs.com/sunshinewxz/p/4518301.html