随手一写,顺便混点黑马币
public class Sum {
/**
* @param args
*/
public static void main(String[] args) {
int[][] a = {{1,2,3},{4,5,6},{7,8,9}};//也可用Scanner输入,为了简便,就不写了
int sum = 0;//用于记录和
for(int i = 0; i < 3; ++i){
sum += a[i][i];
}
System.out.println("主对角线的和是:"+sum);
for(int i = 0; i < 3; i++){
for(int j = 0; j<3; j++){
if((i + j) == 2){//i+i=2时,为副对角线元素,a[0][2],a[1][1],a[2][0]
sum +=a[i][j];
}
}
}
System.out.println("两条对角线的和是:"+sum);
}
} |