首页 > 代码库 > HW7.2

HW7.2

技术分享

 

 1 import java.util.Scanner; 2  3 public class Solution 4 { 5     public static void main(String[] args) 6     { 7         Scanner input = new Scanner(System.in); 8         int[][] matrix = new int[4][4]; 9         System.out.println("Enter a 4-by-4 matrix row by row: ");10         for(int i = 0; i < 4; i++)11             for(int j = 0; j < 4; j++)12                 matrix[i][j] = input.nextInt();13 14         input.close();15 16         System.out.println("Sum of the elements in the major diagonal is " + sumMajorDiagonal(matrix));17     }18 19     public static int sumMajorDiagonal(int[][] m)20     {21         int sum = 0;22         for(int i = 0; i < 4; i++)23             sum += m[i][i];24         return sum;25     }26 }

 

HW7.2