1 /*29 【程序 29 求矩阵对角线之和】 2 题目:求一个 3*3 矩阵对角线元素之和 3 程序分析:利用双重 for 循环控制输入二维数组,再将 a[i][i]累加后输出。 4 */
5
6 /*分析 7 * 1、从键盘得到一个二维数组 8 * 2、累加对角线元素 9 * */
10
11 package homework; 12
13 import java.util.Scanner; 14
15 public class _29 { 16
17 public static void main(String[] args) { 18 // 声明一个二维数组a
19 int[][] a = new int[3][3]; 20 System.out.println("请输入一个3*3的整型二维数组:"); 21 // 利用for循环为二维数组赋值
22 for (int i = 0; i < a.length; i++) { 23 for (int j = 0; j < a[i].length; j++) { 24 a[i][j] = new Scanner(System.in).nextInt(); 25 } 26 } 27 //声明和s
28 int s=0; 29 //输出二维数组
30 for (int i = 0; i < a.length; i++) { 31 for (int j = 0; j < a[i].length; j++) { 32 System.out.print(a[i][j]+" "); 33 } 34 System.out.println(); 35 s=s+a[i][i]; 36 } 37 System.out.println("二维数组对角线和为:"+s); 38
39 } 40
41 }