gpt4 book ai didi

java - 循环代码导致堆栈溢出

转载 作者:行者123 更新时间:2023-12-01 11:02:45 25 4
gpt4 key购买 nike

我有这个代码:

 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)

最佳答案

如果

if(color.getRed() >= 75 && color.getGreen() < 100 )

已满,您将无限调用 Detect 方法。

我建议您检查您的 RGB 值,如果它始终返回 true,请更正测试。

来源:Recursion

The job of the recursive cases can be seen as breaking down complex inputs into simpler ones. In a properly designed recursive function, with each recursive call, the input problem must be simplified in such a way that eventually the base case must be reached. (Functions that are not intended to terminate under normal circumstances—for example, some system and server processes—are an exception to this.) Neglecting to write a base case, or testing for it incorrectly, can cause an infinite loop.

关于java - 循环代码导致堆栈溢出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33209610/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com