0

I am a Java beginner and have recently started playing this thing called 'code fights', they gave me a problem and while writing my response it kept giving me an error message for line 6, saying "ArrayIndexOutOfBoundsException". I put a copy of the problem they gave me at the problem. Any advice would be so appreciated! I have been stuck on this problem for days!

int matrixElementsSum(int[][] matrix) {
int row, column;
int sum=0;
for (row=0;row<3;row++){
    for (column=0;column<4;column++){
        if (matrix[row][column]==0){
            for (column=0;column<3;column++){
                matrix[row][column]=0;
            }
        }
    }
}
for (row=0;row<3;row++){
    for (column=0;column<4;column++){
        sum=sum+matrix[row][column];
    }
}
return sum;

}

After they became famous, the CodeBots all decided to move to a new building and live together. The building is represented by a rectangular matrix of rooms. Each cell in the matrix contains an integer that represents the price of the room. Some rooms are free (their cost is 0), but that's probably because they are haunted, so all the bots are afraid of them. That is why any room that is free or is located anywhere below a free room in the same column is not considered suitable for the bots to live in.

Help the bots calculate the total price of all the rooms that are suitable for them.

for :

matrix = [0, 1, 1, 2], 
         [0, 5, 0, 0], 
         [2, 0, 3, 3]

The output should be : matrixElementsSum(matrix) = 9.

Andy
  • 39,764
  • 8
  • 53
  • 80
  • int sum = 0; for (int i = 0; i < matrix.length); i++) { for (int j = 0; j < matrix[i].length; j++) { sum += matrix[i][j]; } } System.out.println(sum); –  Nov 28 '17 at 00:20
  • Don't use literals in your code, replace them by appropriate method calls or fields that will give back the size of the object. –  Nov 28 '17 at 00:21

0 Answers0