Search code examples
javaarraysindexoutofboundsexceptionsubtraction

Array element subtraction index out of bounds


Im trying to subtract the same element from a different array i.e., [0,0] - [0,0] and [0,1] - [0,1] but I'm just getting an array index out of bounds exception and I can't seem to work out why. Can anyone see a problem with the code?

//pixArray and avgPix already contain data
int[][] pixArray = new int[35][10];
int[][] avgPix = new int[35][1];
int[][] correctImg = new int[35][10];

public void correctImage() {
for (int r = 0; r < correctImg.length; r++) {
        for (int c = 0; c < correctImg[r].length; c++) {
            correctImg[r][c] = avgPix[r][c] - pixArray[r][c];
            System.out.println(correctImg[r][c]);
        }
}
}

I also need to change the loop so that avgPix only loops every time the pixArray column is 0 because avgPix only has 1 column can anyone suggest how I can do this?


Solution

  • You are running r and c based on correctImg's dimension [35][10] and avgPix has dimensions of [35][1]

      int[][] avgPix = new int[35][1];
    

    The loop in the provided code snippet uses r and c value from the outer/inner for loop, based on what's described in the question it will make sense to use avgPix[r][0] for all pixArray[r][c].

    Not sure what you are trying to achieve but something like this will calculate difference with average

       correctImg[r][c] = avgPix[r][0] - pixArray[r][c]