【问题标题】:Array out of Bounds Exception when populating 2D Array maze填充 2D 阵列迷宫时出现阵列越界异常
【发布时间】:2018-01-20 15:03:14
【问题描述】:

我目前正在准备学习数据结构课程,因此我已经开始阅读某些主题。我目前正在学习 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);
    }

据我所知,这一行采用创建的每个标记并填充列。但是,我不确定为什么会出现异常。

感谢您的阅读,希望我能从你们那里得到一些见解。

【问题讨论】:

  • 该错误意味着您正在尝试访问大于数组大小的数组索引。这很容易调试,只需将打印语句添加到问题循环并查看它在哪个索引处中断

标签: java arrays stack indexoutofboundsexception


【解决方案1】:

变化

   Scanner filescan = new Scanner(path);

    Scanner filescan = new Scanner(file);

路径是String 变量而不是File 实例。

【讨论】:

  • 您只需添加一个简单的System.out.println(line);
  • @JyCan12 如果您的问题得到解决,请接受 aristotll 的回答。干杯
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-12-23
  • 2019-10-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-04-13
  • 2014-03-22
相关资源
最近更新 更多