如何在solveMaze函数(java)中使用我的数组?

时间:2016-02-06 06:40:15

标签: java function scope

这是我的代码:

public class solving {
    public static void main(String[] args) throws FileNotFoundException {
        readMazeFile("maze0.txt");
        solveMaze(0, 0);
     }





static void 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;
             }
          }
       }


    static boolean solveMaze(int row, int col) {
      char right = maze[row][col + 1];
      char left = maze[row][col - 1];
      char up = maze[row - 1][col];
      char down = maze[row + 1][col];
      //Base case is at the end of the maze
      if (right == 'E' || left == 'E' || up == 'E' || down == 'E'){
         return true;
      }
      if (right == ' '){
         return solveMaze(row, col+1);
      }

      if (down == ' ') {
         return solveMaze(row+1,col);
  } 

      if (left == ' ') {
         return solveMaze(row,col-1);
  } 

       if (up == ' ') {
          return solveMaze(row-1,col);
  }

      return false;
}





  }

我正在尝试解决使用文本文件创建的迷宫,我确信我的代码还有许多其他问题,但我无法测试它,因为我不知道如何让迷宫数组到在solveMaze函数内部工作。非常感谢任何帮助,谢谢。

1 个答案:

答案 0 :(得分:0)

您有两种选择:

  1. 通过在readMaze()函数之外定义它,然后在solveMaze()函数中使用它来使其全局化。

    public class solving {
        /* Define it here */
        private static char maze[][] = new char[finalHeight][finalWidth];
    
        /* Rest of the code */
    }
    
  2. 将其从readMaze()返回到主函数,然后将其从主函数传递到solveMaze()函数中。

    主要功能:

    public static void main(String[] args) throws FileNotFoundException {
        char[][] maze = readMazeFile("maze0.txt");
        solveMaze(maze, 0, 0);
    }
    

    ReadMaze功能:

    static char[][] readMazeFile(String mazeFile) throws FileNotFoundException {
    
        /* Rest of the code */
    
        /* Return maze array */
        return maze;
    }
    

    SolveMaze功能:

    static boolean solveMaze(char[][] maze, int row, int col) {
        /* Code Here */
    }