Reputation: 1717
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
Upvotes: 0
Views: 286
Reputation: 68847
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.
Upvotes: 1
Reputation: 62759
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.
Upvotes: 0
Reputation: 19352
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;
Upvotes: 3
Reputation: 10393
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);
}
Upvotes: 1