-1

I must create a void method that increments the value of a certain row of a 2D array by 1. The row number is one of the paremeters of the method. For example, if arr is {1, 2}, {3, 3}, {1, 2}, increaseValuesOfARowByOne(arr, 3) outputs {1, 2}, {3, 3}, {2, 3}. Here is my code so far:

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

For the example I mentioned above, I end up getting {1, 2}, {3, 3}, {3, 4}. In other test cases I get ArrayIndexOutOfBoundsException. Not sure what to do.

hjg
  • 1
  • 2
  • What are those other test cases? – f1sh Jan 14 '20 at 16:03
  • 1
    Since indexes in Java are 0-based, `increaseValuesOfARowByOne(arr, 3)` would cause `ArrayIndexOutOfBoundsException` with that 3-row array. – Andreas Jan 14 '20 at 16:05
  • 1
    Remove the first loop `for (int k = 0; k < rowNum; k++)`, why is it even in there? – f1sh Jan 14 '20 at 16:05
  • you don't need 2 loops, as you don't need to traverse the entire 2D array. Just "go to" `rowNum` and increment it – diginoise Jan 14 '20 at 16:06
  • That first loop is why the answer is off – Tyler Jan 14 '20 at 16:06
  • 2
    *"Not sure what to do."* **Debug** your code: [What is a debugger and how can it help me diagnose problems?](https://stackoverflow.com/q/25385173/5221149) – Andreas Jan 14 '20 at 16:08

1 Answers1

0

After all the impovements discribed in the comments, you will get something like this:

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