我有這樣的代碼:循環代碼導致堆棧溢出
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! –
@ArshadAli補充說。 – meganukebmp
你可以用你收到的相同參數調用'Detect(args)'。顯然這會造成無限循環。你必須用不同的參數來調用它(即創建一個參數副本,然後修改/減少該副本)。 – hoijui