我在寻路方面遇到问题:
起点为 0,0,终点为右下角的“C”。它在
处抛出一个异常java.lang.StackOverflowError
if(getPath(x, y+1)==true){
return true;
}
和
if(getPath(x, y-1)==true){
return true;
}
方法如下
public static boolean getPath(int x,int y, int num){
if(x==startX-1|| y==startY-1 || x==endX+1 || y==endY+1){
return false;
}
if (" C".equals(array[x][y])){
return true;
}
if ("# ".equals(array[x][y])||"x".equals(array[x][y])){
return false;
}
if ("[]".equals(array[x][y])){
array[x][y]="+";
}
if(getPath(x, y+1,num)==true){ //vpravo
return true;
}
if(getPath(x+1, y,num)==true){ //dolu
return true;
}
if(getPath(x-1, y,num)==true){ //nahoru
return true;
}
if(getPath(x, y-1,num)==true){ //vlevo
return true;
}
if("+".equals(array[x][y])){
array [x][y]="x";
}
return false;
}
}
我使用的值(value)观
public static Random r = new Random();
public static int i1 = r.nextInt(4) + 4;
public static int startX=0;
public static int startY=0;
public static int endX=i1-1;
public static int endY=i1-1;
public static int rows = i1;
public static int columns = i1;
public static String[][] array = new String[rows][columns];
我有 i3-i14 用于随机障碍,它们是这样定义的
public static int i3 = r.nextInt(4) ;
...
public static int i14 = r.nextInt(4) ;
在我更改比较后,它仍然抛出异常
编辑:我想我已经找到问题了。当 IF 比较“+”并将其替换为“x”时
if("+".equals(array[x][y])){
array [x][y]="x";
你能帮我解决这个问题吗?谢谢
最佳答案
首先,您需要使用 .equals(.)
进行字符串比较,而不是 ==
。
试试这个老栗子:
How do I compare strings in Java?
之后,避免重新跟踪步骤的逻辑可能会开始起作用,并且您可以避免失控的递归。
关于java - 寻路 - StackOverflowError,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30345613/