写了一个,效率不是很好,但是功能实现了
package test;
public class ArraySum {
private int [][] numbers;
private int [] rowSum;
private int [] colmSum;
private int [] diagonalSum;
public ArraySum() {
this.numbers = new int[][]{
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
this.rowSum = new int[3];
this.colmSum = new int[3];
this.diagonalSum = new int[2];
}
void getRowSum() {
for (int i = 0; i < this.numbers.length; i++) {
for (int j = 0; j < this.numbers.length; j++) {
this.rowSum[i] = this.rowSum[i] + this.numbers[i][j];
}
}
}
void getColmSum() {
for (int i = 0; i < this.numbers.length; i++) {
for (int j = 0; j < this.numbers.length; j++) {
this.colmSum[j] = this.colmSum[j] + this.numbers[i][j];
}
}
}
void getDiagonalSum() {
this.diagonalSum[0] = numbers[0][0] + numbers[1][1] + numbers[2][2];
this.diagonalSum[1] = numbers[0][2] + numbers[1][1] + numbers[2][0];
}
void printResult() {
System.out.println("The sums of the rows are as following:");
for (int i = 0; i < this.rowSum.length; i++) {
System.out.print(this.rowSum[i]);
System.out.print(",");
}
System.out.println();
System.out.println("The sums of the colomns are as following:");
for (int i = 0; i < this.colmSum.length; i++) {
System.out.print(this.colmSum[i]);
System.out.print(",");
}
System.out.println();
System.out.println("The sums of the diagonalSum are as following:");
for (int i = 0; i < this.diagonalSum.length; i++) {
System.out.print(this.diagonalSum[i]);
System.out.print(",");
}
System.out.println();
}
public static void main(String[] args) {
ArraySum application = new ArraySum();
application.getColmSum();
application.getRowSum();
application.getDiagonalSum();
application.printResult();
}
}