0

I have a program that uses a java.awt robot to get a picture of the screen and then cycle through the pixels and categorize certain colors in blocks in a list of lists of integer arrays. I have a List<List<int[]>> blocks. The first List is a list of all the blocks, the second list is a list of all the pixels in the blocks, and the integer array is 2 value that are the x and y of the pixel. I first tried to use a for loop through all the blocks with list.contain's to find the array, but that always returned false. I am trying now to use a loop like this to find them.

boolean continuer = false;
boolean found = false;
for (List<int[]> thisBlock : blocks) {
    int[] newInt = new int[2];
    newInt[0] = i;
    newInt[1] = j;
    for (int[] thisInt : thisBlock) {
        if (thisInt == newInt) {
            continuer = false;
            found = true;
            System.out.println("Found pixel in block");
            break;
        }
        if (found) {
            break;
        }
    }
    if (found) {
        break;
    }
}
if (!found) {
    continuer = true;
}

This also returned false always. Any help would be greatly appreciated.

VIAGC
  • 639
  • 6
  • 14
Mr_ME23
  • 1
  • 3
  • 2
    You don't compare arrays like this: `thisInt == newInt`. That tests if two array references point to the same array. See https://stackoverflow.com/questions/14897366/comparing-two-integer-arrays-in-java. (But in that context, I don't think you should be comparing arrays at all. You should be comparing the array contents with `i` and `j`.) – Stephen C May 22 '21 at 03:55
  • You also have a redundant test. And the `continuer` logic looks *weird* to me. – Stephen C May 22 '21 at 03:57
  • As a meta-suggestion, I suggest you read https://rubberduckdebugging.com/ ... and apply those ideas to your approach to debugging your own code. – Stephen C May 22 '21 at 04:01
  • @StephenC I have an if continuer after that that runs a whole other code that works find, sorry for the inconvenience. – Mr_ME23 May 22 '21 at 04:04
  • I don't understand what you just said there. But the main problem in your code is per my first comment. 1) That's the wrong way to compare arrays by value, and 2) you probably should be comparing arrays by value anyway. – Stephen C May 22 '21 at 04:06
  • Alright, thanks, your solution worked, I didn't even think it was my arrays but I guess it makes sense. – Mr_ME23 May 22 '21 at 04:14

1 Answers1

1

Arrays cannot be compared with == operator. There are methods that Arrays Class provides to perform operations on Arrays. Use Arrays.equals(thisInt,newInt) instead of thisInt == newInt

Satwik
  • 11
  • 2
  • In this case, the OP shouldn't compare arrays at all. A better solution is `if (thisInt[0] == i && thisInt[1] == j) {` – Stephen C May 22 '21 at 08:12