题目:求一个3*3矩阵对角线元素之和
1 public class _029MatrixSum { 2 3 public static void main(String[] args) { 4 matrixSum(); 5 } 6 7 private static void matrixSum() { 8 Scanner scanner = new Scanner(System.in); 9 int[][] a = new int[3][3]; 10 System.out.println("请输入9个整数:"); 11 12 for (int i = 0; i < 3; i++) { 13 for (int j = 0; j < 3; j++) { 14 a[i][j] = scanner.nextInt(); 15 } 16 } 17 18 System.out.println("输入的3*3矩阵是:"); 19 for (int i = 0; i < 3; i++) { 20 for (int j = 0; j < 3; j++) { 21 System.out.print(a[i][j] + " "); 22 } 23 System.out.println(); 24 } 25 26 int sum = 0; 27 for (int i = 0; i < 3; i++) { 28 for (int j = 0; j < 3; j++) { 29 if (i == j) { 30 sum += a[i][j]; 31 } 32 } 33 } 34 35 System.out.println("对角线之和是:" + sum); 36 } 37 }