【问题标题】:Printing out the sum of rows in a 2D array using a loop使用循环打印出二维数组中的行总和
【发布时间】:2021-06-10 00:14:32
【问题描述】:

我想先打印出我的数组,然后是每一行的总和,在我的完整数组之后,使用嵌套的 for 循环。但是,在我的第一个嵌套 for 循环将值分配给我的二维数组之后,似乎没有其他任何事情发生。我希望它看起来像: 第一行的总和是:... 第 2 行的总和为 ... 以此类推,直到最后一行。 这是我目前所拥有的。

我的代码:

public class RowsSum {
    public static void main(String[] args) {
        int num = 1;
        int[][] nums = new int[5][3]; //declaring a 2D array of type int
        for (int i = 0; i <= nums.length; i++) {
            for (int j = 0; j < nums[0].length; j++) {
                num *= 2;
                nums[i][j] = num;
                System.out.print(nums[i][j] + "\t");
            }//closing inner loop
            System.out.println("");
        }// closing nested for loop
        int sum = 0;
        int row = 0;
        for (int i = 0; i <= nums.length; i++) { //second nested for loop
            row++;
            for (int j = 0; j < nums[0].length; j++) {
                sum = sum + nums[i][j];
            }//closing inner loop
            System.out.println("The sum of the " + row + "is" + sum + "\t");
            System.out.println("");
        }// closing nested for loop
    }// closing main method
}//closing class

【问题讨论】:

    标签: java multidimensional-array nested-loops


    【解决方案1】:

    在遍历行之前,您不会将 sum 变量重新初始化为 0。此外,不清楚你的第二个双 for 循环试图用这段代码完成什么:

    num *= 2;
    nums[i][j] = num;
    

    这个重复的代码实际上是在改变数组中的值,你应该删除它,它会造成不必要的影响。

    调整为:

    for (int i = 0; i <nums.length; i++){ //second Outer loop
      sum = 0;
      for (int j = 0; j < nums[0].length; j++){ 
        sum = sum + nums[i][j];          
      }//closing inner loop
      
      System.out.println("The sum of row " + (i+1) + " is " + sum);
    }
    

    此外,嵌套的 for 循环实际上是内部循环而不是外部循环。

    编辑:您实际上也在访问原始数组的边界之外,特别是在外部循环中。你有这个:

    for (int i = 0; i <= nums.length; i++)
    

    改成这样:

    for (int i = 0; i < nums.length; i++)
    

    请注意

    【讨论】:

    • 当我这样做时,它仍然不会从第二个嵌套循环中打印出任何内容。它只打印第一个嵌套循环的数组值。
    • 您实际上是在 2D 数组的边界之外访问,当我运行代码时,我得到了一个 arrayOutOfBounds 异常,它告诉了我这一点。有关更多信息,请参阅我的答案中的编辑。另外,作为一般说明,熟悉在您最喜欢的 IDE 中进行调试,这会很有帮助。
    • 之后您什么也没看到的原因是因为您的程序由于错误而提前终止。
    • 哦,我明白了!非常感谢!这正是我正在寻找的。​​span>
    • 当然!附带说明一下,在您使用 C 语言工作并且越界访问不一定会引发错误之前,使用 java 拥有这种奢侈是很高兴的。
    猜你喜欢
    • 1970-01-01
    • 2013-08-02
    • 1970-01-01
    • 1970-01-01
    • 2020-12-03
    • 2015-06-12
    • 1970-01-01
    • 1970-01-01
    • 2015-02-03
    相关资源
    最近更新 更多