[英]Array Out of Bounds Exception in 2D array - how can I avoid this?
我是Java的初学者,我正在编写一个程序来解决迷宫问题,作为一项任务。 现在,我很难处理某些从cvs文件读取迷宫的部分非常愚蠢的事情,但我只是无法解决。
由于某种原因,我说“ while (info[x] != null) {
”的行出现ArrayOutOfBounds
异常。 我需要检查array元素是否为空,否则程序无法运行,但无法正常工作。 有任何想法吗?
public class Project5v2
{
static String mazecsv = "/Users/amorimph/Documents/COMP 182/Project 5/mazeinput.csv";
static File solvedMaze = new File("/Users/amorimph/Documents/COMP 182/Project 5/solvedMaze.txt");
static int[][] maze = new int[50][50];
static int trigger = 0;
static int mazeWidth;
static int mazeHeight;
public static void main(String[] args) {
readCSV(mazecsv);
start(maze);
mazeToString(maze);
}
public static void readCSV(String csvfile) {
BufferedReader br = null;
String line = "";
String csvSplitBy = ",";
int x = 1;
int y = 0;
try {
br = new BufferedReader(new FileReader(csvfile));
br.readLine();
while ((line = br.readLine()) != null) {
String[] info = line.split(csvSplitBy);
while (info[x] != null) {
maze[x][y] = Integer.parseInt(info[x]);
x++;
mazeWidth = x;
}
y++;
x = 1;
mazeHeight = y;
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (br != null) {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
将此更改为for loop
while (info[x] != null) {
maze[x][y] = Integer.parseInt(info[x]);
x++;
mazeWidth = x;
}
至:
for (int x = 0; x < info.length; x++) {
maze[x][y] = Integer.parseInt(info[x]);
}
mazeWidth = info.length;
这是假设info
不会大于50
(这是您为maze
定义的大小)。 如果不能保证,那么
for (int x = 0; x < info.length && x < maze.length; x++) {
您在该行上遇到错误,因为没有什么可以阻止x递增到迷宫中最大行值以外的数字。 因此,如果要保留while循环,可以做的一件事是添加另一个条件。
只需将其添加到您的while循环中即可,如果需要,IFF可以保留一会儿。
while(info[x] != null && x < maze.length)
{
//magicalness
}
附加的布尔语句通过确保x不大于2D数组中的行数或称为info的数组的长度来防止OutOfBounds错误。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.