0

So when I execute this code it should get the rgb number for every pixel of my screen, but for some reason when it reaches the if condition, even though the console displays the exact same rgb number it is trying to compare, nothing seem to happen

for (int i=0; i<image.getWidth()-1; i++){
    x += 1;
    int y = 0;
    for (int j=0; j<image.getHeight()-1; j++){
        y += 1;
        int c = image.getRGB(x,y);
        int  red = (c & 0x00ff0000) >> 16;
        int  green = (c & 0x0000ff00) >> 8;
        int  blue = c & 0x000000ff;
        // and the Java Color is ...
        Color color = new Color(red,green,blue);
        Color iron = new Color(50,26,17);
        Color iron2 = new Color(7,5,16);
        System.out.println(color);
        if (color == iron2){
            Robot move = new Robot();
            move.mouseMove(x,y);
            System.out.println(iron2);
        }
    }
}

Image terminal

Hovercraft Full Of Eels
  • 283,665
  • 25
  • 256
  • 373
  • 1
    Don't compare Colors using `==` or `!=`. Use the `equals(...)` method instead. Understand that `==` checks if the two *object references* are the same which is not what you're interested in. The equals method on the other hand check if the two Colors have the same basic characteristics (the same R, B, G values), and that's what matters here. – Hovercraft Full Of Eels Jul 23 '22 at 23:28
  • So not, `if (color == iron2){` but rather do, `if (color.equals(iron2)) {` – Hovercraft Full Of Eels Jul 23 '22 at 23:31
  • You're welcome. More importantly, the same issue can occur with any non-enum reference type, in particular, Strings. – Hovercraft Full Of Eels Jul 23 '22 at 23:34
  • why cant I use the operator || in this case? for example if (color.equals(iron2 || iron)) it says The operator || is undefined for the argument type(s) java.awt.Color, java.awt.Color, what can I do? – Daniel Lucas Jul 23 '22 at 23:35
  • That is not valid Java syntax, pure and simple. You need valid boolean statements on the left and right hand of the AND or OR operator, e.g., `if (color.equals(foo) || color.equals(bar)) {` – Hovercraft Full Of Eels Jul 23 '22 at 23:36
  • One last thing, is there a way to declare a variable to be in a certain range? for example Color iron = new Color(50<100,26<70,17<40); that won't work but it means r: range from 51 to 99, g 27 to 69 and b 18 to 39. is there a proper way to do it? – Daniel Lucas Jul 23 '22 at 23:41
  • 1
    Your questions are about some of the most basic concepts of Java syntax and are best answered by studying a decent tutorial series and/or text book. – Hovercraft Full Of Eels Jul 23 '22 at 23:42
  • Also look up "input validation" because you will probably want to find a way to validate and restrict the input, the source of the color parameters, for your last request to work. – Hovercraft Full Of Eels Jul 23 '22 at 23:46

0 Answers0