Home > Net >  How can I break this loop properly in Java
How can I break this loop properly in Java

Time:08-11

I am writing code that takes a picture of the screen and then checks pixel by pixel looking for a certain RGB value. Then I want to make it so that it clicks once on that RGB value and then breaks, but for some reason the loop keeps running through all the pixels, ignoring the break command that I put in and clicking on all the pixels of that color instead of clicking once. Any solutions?

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(0,255,0);
        
        if (color.equals(iron)){
            Robot move = new Robot();
            move.mouseMove(x,y);
            Thread.sleep(500);
            move.mousePress(InputEvent.BUTTON1_DOWN_MASK);
            move.mouseRelease(InputEvent.BUTTON1_DOWN_MASK);
            System.out.println(iron);
            break;
        }
    }
}

CodePudding user response:

what you can do is create a flag variable outside your 1st for loop and set it as false. In your 1st loop check if the flag is true and if the condition is true break the loop, in the else part you can run you're second for loop, and when the condition is true in your 2nd loop. set the flag high and break the inner loop.

flag = false;
for (int i=0; i<image.getWidth()-1; i  ){
   if(flag)
      break;
   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(0,255,0);
    
        if (color.equals(iron)){
            Robot move = new Robot();
            move.mouseMove(x,y);
            Thread.sleep(500);
            move.mousePress(InputEvent.BUTTON1_DOWN_MASK);
            move.mouseRelease(InputEvent.BUTTON1_DOWN_MASK);
            System.out.println(iron);
            flag = true;
            break;
        }
    }
}

CodePudding user response:

As some people said, you can use a flag.

I often just extract the code into a new method and return the result. So in your case, you have to put the 2 for loops into another method, giving the proper parameters and return at the "break" statement.

You can return a boolean, which is true, when the program entered the if-statement and false, if it didn't enter the if-statement. But of course it can basically return anything you want.

  • Related