编写一个测试程序,读取一个3*4的矩阵,然后显示每列元素的和。
import java.util.Scanner;
public class HomeWork5 {
public static double sumColumn(double[][] m, int columnIndex) {
double sum = 0.0;
for(int i=0; i<3; i++) {
sum+=m[i][columnIndex];
}
return sum;
}
public static void main(String[] args) {
Scanner input = new Scanner( System.in );
double[][] array = new double[3][4];
System.out.println("Enter a 3-by-4 matrix row by row:");
for(int i=0; i<3; i++)
for(int j=0; j<4; j++) {
array[i][j] = input.nextDouble();
}
for(int i=0; i<4; i++) {
System.out.println("Sum of the elements at column " + i + " is "+sumColumn(array,i));
}
input.close();
}
}
运行结果: