无法正确获取行总和。我没有得到正确行的总和

问题描述 投票:0回答:2
    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

我的输出仅略有偏离,我无法弄清楚如何克服它或找到更好的解决方案。

java multidimensional-array
2个回答
1
投票
您需要在求和后将其打印出来

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; }


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; }
© www.soinside.com 2019 - 2024. All rights reserved.