Out of bounds exception in double dimensional array

1.9k Views Asked by At

Trying to find the sum of all even numbers and product of all odd numbers in a double dimensional array.

Why am I getting the following out of bounds exception error ?

Exception java. lang. Array Index Out Of Bounds Exception

While running the code this exception comes for line if(m[i][j]%2==0)

photo of code

3

There are 3 best solutions below

0
ihatecsv On

Your m array's element at index 1 is missing a fourth element:

{30,11,71}
3
Tim Biegeleisen On

The exact cause of your error is that your 2D array is actually a jagged array, meaning that not every row contains the same number of elements. In fact, the second row only contains three elements, so when you when the following if check:

if (m[i][j]%2 == 0)

you get an out of bounds exception for i=1 and j=3.

You should either make the 2D array non-jagged, or instead use this for loop:

for (int i=0; i < 4; ++i) {
    for (int j=0; j < m[i].length; ++j) {
            if (m[i][j]%2 == 0) {
                s += m[i][j];
            }
            else {
                r *= m[i][j];
            }
        }
    }
}
1
lealceldeiro On

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