-3

OOB Exception. How to debug?

        int sum[]= new int[4], ctr = 0, sums=0;
        for(int row=0;row<x.length;row++){
            int col = 0;
            for(int column=0;column<x[row].length;column++){
                sum[row] += x[row][column];
                sums += x[row][column];
                col += x[column][row];
            }
            ctr++;
            System.out.println("The sum of column " + ctr +": " + col);
            System.out.println("The sum of row " + ctr +": " + sum[row]);
        }
        System.out.println("The sum of all arrays: "+sums);

    }
}

This is the code. The problem lies within col += x[column][row]; I'm stuck, Please help. Thanks

zkyb
  • 1
  • 3
  • possible duplicate of [What causes a java.lang.ArrayIndexOutOfBoundsException and how do I prevent it?](http://stackoverflow.com/questions/5554734/what-causes-a-java-lang-arrayindexoutofboundsexception-and-how-do-i-prevent-it) – Raedwald Apr 11 '15 at 07:26

2 Answers2

1

Here:

for(int column=0;column<x[row].length;column++){
    sum[row] += x[row][column];
    sums += x[row][column];
    col += x[column][row];
}

You have more rows than you do columns.

So do this to catch it:

for(int column=0;column<x[row].length;column++){
    sum[row] += x[row][column];
    sums += x[row][column]

    if (row < x[row].length){
        col += x[column][row];
    }
}
P M
  • 189
  • 1
  • 11
  • Thankyou so much! i get it now with the help of "Hence x[0][3] will give you OOB exception." from AJ. Thank you guys! – zkyb Apr 11 '15 at 07:17
0

Just add this line in your code

 System.out.println(column+" "+row);
 col += x[column][row];

After running your code.. at the end, row value becomes 3

Hence x[0][3] will give you OOB exception.

You have to handle col += x[column][row]; in some condition so that it never gets executed if row exceeds the value 3

AJ.
  • 4,309
  • 5
  • 27
  • 39
  • so how do i remove OOB exception? and please explain it further. bear with my ignorance. Thanks for the answer – zkyb Apr 11 '15 at 06:49