자바에서 if-else 문에 이상한 문제가 있습니다. 아래는 getPathThroughMaze라는 미로의 끝을 찾으려고 시도하는 재귀 적 메서드입니다.이상한 if 문 동작이 자바에서
내가 문제로 실행하는 재귀의 시점에서private static String getPathThroughMaze(char[][] maze, Set<Point> visited, Point currentPoint) {
int currentX = currentPoint.x;
int currentY = currentPoint.y;
visited.add(currentPoint);
//end case. append '!' so we know which path leads to the end of the maze
if (currentX == (xLength - 2) && currentY == (yLength - 1)) {
return "!";
}
char left = maze[currentY][currentX - 1];
char right = maze[currentY][currentX + 1];
char up = maze[currentY - 1][currentX];
char down = maze[currentY + 1][currentX];
char current = maze[currentY][currentX];
/* If valid, visit all non-visited adjacent squares.
Only odd numbered columns will be traversed
since even numbered columns represent vertical wall
columns
*/
if (right == '_' || right == ' ') {
Point nextPoint = new Point(currentX + 2, currentY);
if (!visited.contains(nextPoint)) {
String path = "E" + getPathThroughMaze(maze, visited, nextPoint);
if (path.endsWith("!")) {
return path;
} else {
//do nothing.
}
}else {
//do nothing.
}
} else if (up == ' ') {
Point nextPoint = new Point(currentX, currentY - 1);
if (!visited.contains(nextPoint)) {
String path = "N" + getPathThroughMaze(maze, visited, nextPoint);
if (path.endsWith("!")) {
return path;
} else {
//do nothing.
}
} else {
//do nothing.
}
} else if (current == ' ' && (down == '_' || down == ' ')) {
Point nextPoint = new Point(currentX, currentY + 1);
if (!visited.contains(nextPoint)) {
String path = "S" + getPathThroughMaze(maze, visited, nextPoint);
if (path.endsWith("!")) {
return path;
} else {
//do nothing.
}
} else {
//do nothing.
}
} else if (left == '_' || left == ' ') {
Point nextPoint = new Point(currentX - 2, currentY);
if (!visited.contains(nextPoint)) {
String path = "W" + getPathThroughMaze(maze, visited, nextPoint);
if (path.endsWith("!")) {
return path;
} else {
//do nothing.
}
} else {
//do nothing.
}
} else {
return "";
}
//otherwise...
return "";
}
변수는 : 다른 첫 번째에서
currentX = 3
currentY = 2
right = '|'
left = '|'
up = ' '
down = '_'
current = ' '
visited contains points (1,1), (3,1), (3,2)
if 문
else if (up == ' ')
새로운 점 (3, 1)은 이미 방문 세트에 포함되어 있습니다. 내가 일이 기대하는 것은
if(!visited.contains(nextPoint))
false로 내가 그 상태를 점검 할 수있는
else if (current == ' ' && (down == '_' || down == ' '))
에 도착 (아마도 디버거에서 클릭을 통해 몇 단계 이후) 나는 것을 평가하는 것입니다 (나는 그것이 진실 일 것을 기대한다). 그리고 미로를 계속 가로 질러 간다. 무엇 실제로 일어나는 일은 내가 (elcipse와 IntelliJ를 모두)
if(!visited.contains(nextPoint))
디버거에 스텝 오버를 클릭하면 내 방법의 맨 마지막 return 문에 모든 방법을 이동하고는 ""를 반환하고자합니다. 왜 다른 모든 else if 문을 건너 뛰고 있는지 이해할 수 없습니다. 그 이유가 누구일까요? 제 설명이 명확하지 않은 경우 알려주십시오.
귀하의 코드 자체는 경우/다른 사람의 미로입니다. 나는 강하게 디자인을 바꾸라고 제안 할 것이다. 이것은 디버그하기가 매우 어렵습니다. – Lokesh