简体   繁体   中英

Array out of Bounds Exception when populating 2D Array maze

I am currently prepping to head into a Data Structures Course and as a result have begun reading on certain topics before hand. I am currently studying up on Stacks but have come across a problem.

I am currently coding a Maze App that uses stacks to auto-solve a maze. However, I am experiencing a problem when it comes populating the maze itself.

Code below:

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();
    }

}

Here is the .txt file

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

The Exception itself occurs at this particular line once col = 2.

for(int col = 1; col <= 10; ++col)
    maze[row][col] = tokens[col-1].charAt(0);
    }

From what I gather, this line takes each token that is created and populates the column. However, I am not sure why I get a exception.

Thanks for reading and hopefully I can get some insight from you guys.

Changes

   Scanner filescan = new Scanner(path);

to

    Scanner filescan = new Scanner(file);

The path is a String variable rather than File instance.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM