ChuckDivebomb
ChuckDivebomb

Reputation: 55

Moving a Java array Through a Larger Array

So for my class I have been tasked with scanning through a large 15x15 matrix for all possible combinations of a 4x4 matrix, both horizontally and vertically. This is what I've come up with, but it returns a null pointer exception. Any advice as to how I could fix this?

public double compareMatrices(int[][] num,int[][] mat){
    int o=0;
    double score=0;

    for(int n=0;n+4<mat.length;n++){
        int[][] rows=new int[4][];
        for(int m=0;m+4<15;m++){
            for(;o<4;o++){
                rows[o]=Arrays.copyOfRange(mat[o], m, m+4);
        }       
            for(int p=0;p<rows.length;p++){
                for(int q=0;q < rows.length;q++){
                    if((rows[p][q]==1)&&(num[p][q]==1)){
                        score+=1;
                    }else if((num[p][q]==1)&&(rows[p][q]==0)){
                        score-=.25;
                    }else if((num[p][q]==0)&&(rows[p][q]==0)){
                        score+=.25;
                    }
                }
            }
        }
    }

    return(score);
}

Upvotes: 0

Views: 94

Answers (2)

Gee858eeG
Gee858eeG

Reputation: 185

In your inner for loop you're incrementing q to rows.length. Unless you're absolutely certain that you have only square matrices you should use rows[0].length in that loop. This could lead to ArrayOutOfBounds Exceptions. But as i see in your code, it works fine the way you did it. Is there a reason for this line o++; in the end of one of your for loops? Because further above you have this:

for(;o<4;o++)
                rows[o]=Arrays.copyOfRange(mat[o], m, m+4);

eventually this situation will lead to a nullpointerexception, since you dont fill your array rows anymore. When your o becomes greater than 4 the for loop will not be executed. And your o becomes greater than 4 in your code. a quick fix would be putting the initialization of that variable into the for loop

for(int o ;o<4;o++)

Upvotes: 1

Sky
Sky

Reputation: 3360

The Null Pointer Exception might be caused when the array index is holding NULL data and while you iterating through the array on a NULL data and compare to some value, it will throw the error.

To solve this issue, check if the array index is NULL first, if it is, skip it or ignore it by doing

if (array[i][j] != null){
        // then do your codes
}

Or

if (array[i][j] == null){
        continue; // skip this null array
}

Upvotes: 0

Related Questions