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];
}
}
我得到的输出是这个[[1、2、3],[4、5、6]]第1行的总和为0第2行的总和为6
我的输出仅略有偏离,我无法弄清楚如何克服它或找到更好的解决方案。
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;
}
//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;
}