Do not use as limits fixed values (such as 4
), but instead use the length
provided by the array(s).
for (int i = 0; i < m.length; i++) {
for (int j = 0; j < m[i].length; j++) {
//...
}
}
Why?
Not all inner arrays have 4 elements (i.e.: {30, 11, 71}
), so at the last iteration of the inner loop (j = 3
), this code m[i][j]
tries to access a value out of the bounds of the array because in some cases there is no position 3
, just 0
(1st element), 1
(2nd element) and 2
(3rd element). Thus you get the mentioned exception.
Side note:
Another problem (mentioned by you) is that you will get r = 0
always because it is initialized to 0
and every time you multiply its value by another one, the result will be 0
.
So, in order to fix this you need to add a check in the else
condition, like this:
else {
r = r == 0 ? m[i][j] : r * m[i][j];
}