Reputation: 15
int[][] userArray = new int[rows][columns]; //Establishing the bounds of the array
for (int i = 0; i < rows; i++) //This is the loop to set the array values
{
System.out.println("Enter row" + (i + 1) + "values");
for (int j = 0; j < columns; j++) //Row value loop
{
System.out.println("Value" + (j + 1) + " is: ");
userArray[i][j] = input.nextInt();
}
}
System.out.println(Arrays.deepToString(userArray));
//This is the loop for for finding the sum of the rows
for (int i = 0; i < rows; i++)
{
System.out.println("Row " + (i + 1) + "'s sum is" + sum);
for (int j = 0; j < columns; j++)
{
sum += userArray[i][j];
}
}
The output that I got was this [[1, 2, 3], [4, 5, 6]] Row 1's sum is0 Row 2's sum is6
My output is only slightly off and I can not figure out how to get past it or find a better solution.
Upvotes: 0
Views: 44
Reputation: 139
When you write:
System.out.println("Row " + (i + 1) + "'s sum is" + sum);
that is the first time you are implicitly declaring sum
, so there is nothing to print but 0. That means the second loop is printing what you meant to output during the first loop. Hint: row 2's output is really the correct output for row 1.
Put the print statement after you set sum
in your final inner loop.
Upvotes: 1
Reputation: 57
//This is the loop for for finding the sum of the rows
for (int i = 0; i < rows; i++)
{
for (int j = 0; j < columns; j++)
{
sum += userArray[i][j];
}
// this should be after the sum has calculated
System.out.println("Row " + (i + 1) + "'s sum is" + sum);
// set to 0 for the next row
sum = 0;
}
Upvotes: 1
Reputation: 44813
You need to print it out after doing the summing
for (int i = 0; i < rows; i++)
{
for (int j = 0; j < columns; j++)
{
sum += userArray[i][j];
}
System.out.println("Row " + (i + 1) + "'s sum is" + sum);
// and then set sum back to zero
sum = 0;
}
Upvotes: 2