# Sum elements column by column

• May 8th, 2013, 01:15 PM
NallelyXIII
Sum elements column by column
Hi!
I have to create this program, and it's working fine, but for some reason I cannot comprehend, it doesn't return doubles
If I try to change:

double total = 0;

the return type is still incorrect.

Any help will be appreciated :)
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ~~~~~~~

import java.util.Scanner;
public class SumElementsByColumn {
public static void main(String[] args) {
double [][] matrix = new double[3][4];

Scanner input = new Scanner(System.in);
System.out.println("Enter " + matrix.length + " rows and " +
matrix[0].length + " columns: ");
for (int row = 0; row < matrix.length; row++){
for ( int column = 0; column < matrix[row].length; column++){
matrix[row][column] = input.nextDouble();
}
}
sumColumn(matrix,0);
}
public static int sumColumn(double[][] m, int columnIndex){
int total = 0;
for ( int column = 0; column <= columnIndex; column++){
total = 0;
for (int row = 0; row < m.length; row++){
total += m[row][column];
}
System.out.println(total);
}
}

}
• May 8th, 2013, 01:28 PM
theoriginalanomaly
Re: Sum elements column by column
You are accumulating into an int. Total is an int, and the methods return type is int.

In other words, change the return type to double, and the total into double.
• May 9th, 2013, 01:22 AM
NallelyXIII
Re: Sum elements column by column
Quote:

Originally Posted by theoriginalanomaly
You are accumulating into an int. Total is an int, and the methods return type is int.

In other words, change the return type to double, and the total into double.

I saw it earlier today!
Such a silly mistake!!
Thanks a lot though! n_n