我目前正在准备学习数据结构类(class),因此已经开始提前阅读某些主题。我目前正在研究 Stacks,但遇到了一个问题。
我目前正在编写一个迷宫应用程序,它使用堆栈来自动解决迷宫。然而,当我填充迷宫本身时,我遇到了一个问题。
代码如下:
import java.io.*;
import java.util.*;
public class Maze {
private Square move;
private char[][] maze;
private SquareStack s;
private String path =
"C:\\Users\\Sigh\\workspace\\StegmannStackMaze\\maze.txt";
private File file = new File(path);
public Maze(){
s = new SquareStack();
maze = new char[12][12];
}
public void getMaze() throws IOException{
for (int row = 0; row < 12 ; ++row){ // Creates the left/right walls of the maze " | | "
maze[row][0] = '1';
maze[row][11] = '1';
}
for ( int col = 0; col < 12 ; ++col){ // Creates upper and lower walls of the maze
maze[0][col] = '1';
maze[11][col] = '1';
}
Scanner filescan = new Scanner(path);
for( int row = 1; row <= 10 ; ++row){
String line = filescan.nextLine();
String delim = "[ ]+";
String[] tokens = line.split(delim);
for(int col = 1; col <= 10; ++col)
maze[row][col] = tokens[col-1].charAt(0);
}
filescan.close();
}
}
这是 .txt 文件
0 0 1 E 1 0 0 1 1 1
0 1 1 0 1 0 1 0 0 0
0 0 0 0 0 0 0 0 1 0
1 1 1 1 1 0 1 1 0 0
0 0 0 1 0 0 0 1 0 1
0 1 0 1 0 1 1 1 0 1
0 1 0 1 0 0 0 1 0 0
1 1 0 1 1 1 0 1 1 0
0 1 0 0 0 0 0 1 1 0
0 1 0 1 1 0 1 0 0 0
一旦 col = 2,异常本身就会发生在该特定行。
for(int col = 1; col <= 10; ++col)
maze[row][col] = tokens[col-1].charAt(0);
}
根据我收集的信息,这一行采用创建的每个标记并填充该列。但是,我不确定为什么会出现异常。
感谢您的阅读,希望我能从你们那里得到一些见解。
最佳答案
更改
Scanner filescan = new Scanner(path);
至
Scanner filescan = new Scanner(file);
路径是一个String
变量而不是File
实例。
关于java - 填充二维数组迷宫时数组越界异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45646311/