[英]Why isn't my function being ran in my program (java)?
該程序應該遞歸解決迷宮。 readMazeFile將文件的內容讀取到數組中,然后solveMaze函數使用該數組來求解迷宮。 但是在我的主要功能中,似乎(maze!= null)似乎沒有運行。 我包括了它以消除空指針異常。 迷宮=空嗎? 我不這么認為,但IDK。 感謝您的幫助。
public class solving {
static char maze[][];
static int startingrow;
static int startingcol;
public static void main(String[] args) throws FileNotFoundException {
readMazeFile("maze0.txt");
if (maze != null) {
System.out.print(maze[1][1]);
if (solveMaze(startingrow, startingcol))
System.out.print("Solved!");
else
System.out.print("There is no solution to this maze.");
}
}
static boolean solveMaze(int row, int col) {
// name each movement to make coding easier to understand with the recursion.
char right = maze[row][col + 1];
char left = maze[row][col - 1];
char up = maze[row - 1][col];
char down = maze[row + 1][col];
char markSpot = 'M';
char unmarkSpot = ' ';
// Base case is at the end of the maze
if (right == 'E' || left == 'E' || up == 'E' || down == 'E') {
return true;
}
// What to do if there is an empty space when it moves
if (right == ' ') {
right = markSpot;
if (solveMaze(row, col + 1)) {
return true;
} else {
right = unmarkSpot;
}
}
if (down == ' ') {
down = markSpot;
if (solveMaze(row + 1, col)) {
return true;
} else {
up = unmarkSpot;
}
}
if (left == ' ') {
left = markSpot;
if (solveMaze(row, col - 1)) {
return true;
} else {
left = unmarkSpot;
}
}
if (up == ' ') {
up = markSpot;
if (solveMaze(row - 1, col)) {
return true;
} else {
up = unmarkSpot;
}
}
return false;
}
static char[][] readMazeFile(String mazeFile) throws FileNotFoundException {
Scanner input = new Scanner(new File(mazeFile));
// Find the height and width
int height = input.nextInt();
int width = input.nextInt();
int finalHeight = (2 * height) + 1;
int finalWidth = (2 * width) + 1;
// Create the array and put data from the file in it
char maze[][] = new char[finalHeight][finalWidth];
input.nextLine();
for (int row = 0; row < finalHeight; row++) {
String fileLine = input.nextLine();
for (int col = 0; col < finalWidth; col++) {
char nextChar = fileLine.charAt(col);
maze[row][col] = nextChar;
}
}
// Find the starting point
for (int r = 0; r < finalHeight; r++) {
for (int c = 0; c < finalWidth; c++) {
if (maze[r][c] == 'S') {
int startingrow = r;
int startingcol = c;
//System.out.print(startingrow);
//System.out.print(startingcol);
}
}
}
return maze;
}
}
readMazeFile
的maze
變量readMazeFile
了您在條件條件中使用的靜態變量。
要么:
readMazeFile
。 readMazeFile
聲明新的maze
變量(刪除char
類型聲明readMazeFile
)。 然后將其返回就不必要了。 您必須將函數調用的結果存儲在變量迷宮的main的第一行中。 由於尚未執行此操作,因此迷宮當然為空。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.