【发布时间】:2015-10-19 08:14:10
【问题描述】:
我有这个代码:
public static void Detect (String[] args) throws Exception {
PointerInfo pointer; /* needed for getting cursor location */
pointer = MouseInfo.getPointerInfo();
Point coord = pointer.getLocation();
Robot cursor = new Robot(); /*Creates a new robot */
cursor.delay(500); /* robot delay */
/**
* detection method
* Works by looking at pixel color underneath mouse.
* If RED is over > a value and GREEN is under < a value then loop
* If criteria is not matched go to Something
*/
while(true) {
coord = MouseInfo.getPointerInfo().getLocation();
Color color = cursor.getPixelColor((int)coord.getX(), (int)coord.getY());
if(color.getRed() >= 75 && color.getGreen() < 100 ){
Detect(args);
}
else{
System.out.println(color);
Something(args);
}
cursor.delay(1000);
}
}
而且我知道这可能是最糟糕的实现方式。调用 void 创建循环会导致堆栈溢出。有人能解释一下我如何让整个代码段做同样的事情,但使用“while”循环吗?
顺便说一句,这里是堆栈跟踪:
Exception in thread "main" java.lang.StackOverflowError
at sun.awt.Win32GraphicsConfig.getBounds(Native Method)
at sun.awt.Win32GraphicsConfig.getBounds(Unknown Source)
at java.awt.MouseInfo.areScreenDevicesIndependent(Unknown Source)
at java.awt.MouseInfo.getPointerInfo(Unknown Source)
at com.meganukebmp.Main.Detect(Main.java:29)
at com.meganukebmp.Main.Detect(Main.java:45)
at com.meganukebmp.Main.Detect(Main.java:45)
at com.meganukebmp.Main.Detect(Main.java:45)
at com.meganukebmp.Main.Detect(Main.java:45)
at com.meganukebmp.Main.Detect(Main.java:45)
at com.meganukebmp.Main.Detect(Main.java:45)
at com.meganukebmp.Main.Detect(Main.java:45)
at com.meganukebmp.Main.Detect(Main.java:45)
at com.meganukebmp.Main.Detect(Main.java:45)
at com.meganukebmp.Main.Detect(Main.java:45)
【问题讨论】:
-
请给我们看stacktrace!
-
您调用
Detect(args)时使用的参数与您收到的相同。显然这将创建一个无限循环。您必须使用不同的参数调用它(即创建参数的副本,然后修改/减少该副本)。
标签: java loops while-loop stack-overflow