二维数组计算4*4矩阵对角线上的元素之和

来源:互联网 发布:windows搭建dns 编辑:程序博客网 时间:2024/06/15 09:21
import java.util.Scanner;


public class Test2DArrayPractice {


public static void main(String[] args) {
// TODO Auto-generated method stub
/*
* 请输入任意一个4*4的矩阵,计算出左右对角线上的元素之和
*/
int[][] array = new int[4][4];

Scanner scan = new Scanner(System.in);
for(int i = 0; i < array.length; i++){
for(int j = 0; j < array[i].length; j++){
System.out.println("请输入第"+(i+1)+"行第"+(j+1)+"列上的元素:");
array[i][j] = scan.nextInt();
}
}

int total = 0;//作为最后存放结构的变量
for(int i = 0; i < array.length; i++){
for(int j = 0; j < array[i].length; j++){
//左对角元素         右对角元素
if(i == j || i +j == 3){
total += array[i][j];
}

}
}


}


}
0 0
原创粉丝点击