1

So far I have a method that totals the columns, but it's not exactly what I need.

I need to have the total of each row to the right of each row, and the total of each column at the bottom of each column. Something like this

1  2  3  4  =  10
3  4  5  6  =  18

4  6  8  10  < - Total

What I have now gives me the total of each column, but not under the columns.

Method

    // method to add the sum of columns
    public static int[] columnSum(int x[][]){
          int temp[] = new int[x[0].length];

            for (int i = 0; i < x[0].length; i++){
                int sum = 0;

                for (int j = 0; j < x.length; j++){
                    sum += x[j][i];

                }
                temp[i] = sum;
                System.out.println("Index is: " + i + " Sum is: "+sum);

            }

            return temp;
        }


}

3 Answers 3

2
This is the array
1   2   3   
2   3   4 
3   5   7

apply just one more for loop after printing the matrix.

System.out.println("This is the sum of the columns");
int temp[]=columnSum(firstarray);
for(int i=0;i<columns;i++)
{
    System.out.print(temp[i]+"\t");
 }
 System.out.println();

replace with

System.out.println("This is the sum of the columns");
columnSum(firstarray);
Sign up to request clarification or add additional context in comments.

10 Comments

So just add this one into the method? I tried doing that, but it wasn't displayed properly. I might be doing something wrong
Yes. But it didn't come out like that. I'll edit above
So paste this for loop after the code where you are printing the matrix.Not in columnSum method.
Still not displaying correctly. Would it be ok if I edited everything above and posted my entire code?
There is no problem if you enter your full code .but indent that in a good manner means should be readable clearly.
|
0

After printing the array, just print the totals in a single line instead of three lines.

4 Comments

I'm not following. I changed println to print, but that doesn't do what I want.
"but that doesn't do what I want." - and what does it?
Ok. I edited to show the output of changing to print
Yes, perhaps you should omit the hint-text. You didn't print additional text when displaying the array, did you?
-1

You can use a stringbuilder to append each sum to a string and then print it out after the loop is over.

StringBuilder columnTotal = new StringBuilder();

for (....){
 columnTotal.append(sum)
}

System.out.println(columnTotal)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.