【发布时间】: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 < rowNum; k++),为什么它还在里面? -
您不需要 2 个循环,因为您不需要遍历整个二维数组。只需“转到”
rowNum并增加它 -
“不确定该怎么做。” 调试你的代码:What is a debugger and how can it help me diagnose problems?
标签: java arrays multidimensional-array methods