【问题标题】:Method to Increment the value of int row elements in a 2D array增加二维数组中 int 行元素值的方法
【发布时间】:2020-05-01 09:35:50
【问题描述】:

我必须创建一个 void 方法,将 2D 数组的某一行的值加 1。行号是该方法的参数之一。例如,如果arr{1, 2}, {3, 3}, {1, 2},则increaseValuesOfARowByOne(arr, 3) 输出{1, 2}, {3, 3}, {2, 3}。到目前为止,这是我的代码:

public static void increaseValuesOfARowByOne(int[][] arr, int rowNum)
  {
    for (int k = 0; k < rowNum; k++)
    {
      for (int j = 0; j < arr[0].length; j++) {
        (arr[rowNum][j])++;
      }

    }
    return;
  }

对于我上面提到的示例,我最终得到{1, 2}, {3, 3}, {3, 4}。在其他测试用例中,我得到 ArrayIndexOutOfBoundsException。不知道该怎么办。

【问题讨论】:

  • 其他的测试用例是什么?
  • 由于 Java 中的索引是从 0 开始的,increaseValuesOfARowByOne(arr, 3) 将导致 ArrayIndexOutOfBoundsException 具有该 3 行数组。
  • 去掉第一个循环for (int k = 0; k &lt; rowNum; k++),为什么它还在里面?
  • 您不需要 2 个循环,因为您不需要遍历整个二维数组。只需“转到”rowNum 并增加它
  • “不确定该怎么做。” 调试你的代码:What is a debugger and how can it help me diagnose problems?

标签: java arrays multidimensional-array methods


【解决方案1】:

在完成 cmets 中描述的所有改进后,您将得到如下结果:

public static void increaseValuesOfARowByOne(int[][] arr, int rowNum) {
    for (int i = 0; i < arr[rowNum - 1].length; i++) {
        arr[rowNum - 1][i]++;
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-04-18
    • 2023-02-25
    • 1970-01-01
    • 2014-10-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-01
    相关资源
    最近更新 更多