[英]How can I break this loop properly in Java
我正在编写拍摄屏幕图片的代码,然后逐像素检查以查找某个 RGB 值。 然后我想让它在那个 RGB 值上单击一次然后中断,但由于某种原因,循环继续运行通过所有像素,忽略我输入的中断命令并单击该颜色的所有像素而不是点击一次。 有什么解决办法吗?
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;
}
}
}
正如某些人所说,您可以使用标志。
我经常只是将代码提取到一个新方法中并返回结果。 因此,在您的情况下,您必须将 2 个 for 循环放入另一个方法中,提供正确的参数并在“break”语句处返回。
您可以返回 boolean,当程序进入 if 语句时返回 true,如果没有进入 if 语句,则返回 false。 但当然它基本上可以返回你想要的任何东西。
其他解决方案也不错,但值得一提的是 java 有一个labeled break
。
所以
ImageLoop:
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 ImageLoop; // <--
}
}
}
您可以做的是在第一个 for 循环之外创建一个标志变量并将其设置为 false。 在你的第一个循环中检查标志是否为真,如果条件为真,则中断循环,在 else 部分你可以运行你的第二个 for 循环,并且当你的第二个循环中的条件为真时。 将标志设置为高并打破内部循环。
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;
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.