tags:

views:

76

answers:

4

Hello everybody

I need help, I got a problem with this matrix, I need to have it in this way:

1 2  3  4 = 10
2 4  6  8 = 20
3 6  9 12 = 30
4 8 12 16 = 40

But I have it in this way:

1 2 3 4 1
2 4 6 8 2
3 6 9 12 3
4 8 12 16 4

I dont know how can we do that, I intent but nothing

This is my code:

public class Matrix {

    public static void main(String args[]) {

        int mult = 4;


        for (int i = 1; i <= mult; i++) {
           // System.out.println();


            for (int j = 1; j <= mult; j++) {
                int operacion = i * j;
                int suma = 0;
                suma = operacion + suma;

                System.out.print(operacion + " ");

            }


            int sum = 0;
            sum = i + sum;
            System.out.println(sum);


        }
    }
}

bye

+1  A: 

Put int sum = 0 outside the second for loop.

 int suma = 0;
for (int i = 1; i <= mult; i++) {
       // System.out.println();
         suma =0;

        for (int j = 1; j <= mult; j++) {
            int operacion = i * j;

            suma = operacion + suma;

            System.out.print(operacion + " ");

        }
        System.out.println(suma);


    }
Praveen S
Thanks for answer, I did not notice that of the sum, I got it
GeorgeBecj
+2  A: 

When you do this:

for (int j = 1; j <= mult; j++) {
    int operacion = i * j;
    int suma = 0;
    suma = operacion + suma;

suma is always equal to operacion, because you set it to 0 every time and then add operacion.

You want to do this:

int suma = 0;
for (int j = 1; j <= mult; j++) {
    int operacion = i * j;
    suma += operacion;
zvonimir
Thanks for answer I didnt notice that, I gonna try to check more my code
GeorgeBecj
A: 

You are resetting sum to 0 just before you use it. You probably want for sum to be reset before your inner loop, added to inside your inner loop and printed outside your inner loop.

Also for your final println, print (" = " + sum) instead of just sum.

Trying not to actually correct your code since you mentioned this is an exercise (homework)--and thank you for tagging it. I wish more answerers would look for that sign as an indication that the person needs to learn and doesn't need the answer coded for them.

Bill K
You got reason thanks for answering
GeorgeBecj
A: 

You should take a look to String.format() or PrintStream.printf(). I think others allready helped you with the sum-problem. So try to print the values out like this:

for (int i = 0; i < 4; i++)
{
    int[] values = new int[4];
    int sum = 0;
    for (int j = 0; j < 4; j++)
    {
        values[i] = (i+1) * (j+1);
        sum += values[i];
    }
    System.out.printf("%-4d%-4d%-4d%-4d = %d\n", values[0], values[1], values[2], values[3], sum); 
}

Try also to remove all the minus signs (-) from the last line and see what you like the most.

Martijn Courteaux
Thanks for asnwering, Its a great help!
GeorgeBecj