0
votes

I am trying to create a program that generates chutes and ladders onto 2D array board that is of size 10X10. In order to generate these chutes and ladders, I had to create a method called readBoard that basically reads a written file (myBoard.csv) and translates the written information into positions and place the chutes and ladders onto the 2D array board accordingly.

The program compiles but when I run it there is this error:

java.lang.ArrayIndexOutOfBoundsException: 1 at ChutesAndLadders.readBoard(ChutesAndLadders.java:41) at TestFile.main(TestFile.java:13) My impression was that perhaps my written file had additional spaces that I didn't see that's why it's telling me I'm out of bound. However, I checked the written file and it looks fine. If you could provide some insight into this problem, that would be great. Thanks in advance!

Here is my getBoardmethod:

public void readBoard(String filename)throws Exception 
{
    Scanner s=new Scanner(new File(filename));
    s.nextInt();
    while (s.hasNext())
    {
        String line=s.nextLine();
        String[]singleSplit=line.split(",");
        String cellType=singleSplit[0];
        int row=Integer.parseInt(singleSplit[1]);
        int col=Integer.parseInt(singleSplit[2]);
        if (cellType.equals("Chute"))
            board[row][col]=new Chute();
        else
            board[row][col]=new Ladder();
    }
}

and here is my written file (type,row,column):

29

Chute,1,0

Chute,2,0

Chute,3,0

Chute,4,0

Chute,5,0

Chute,6,0

Chute,7,0

Chute,8,0

Chute,9,0

Chute,0,1

Chute,0,2

Chute,0,3

Chute,9,1

Chute,9,2

Chute,9,3

Ladder,0,5

Ladder,1,5

Ladder,2,5

Ladder,3,5

Ladder,4,5

Ladder,5,5

Ladder,6,5

Ladder,7,5

Ladder,8,5

Ladder,9,5

Ladder,9,6

Ladder,9,7

Ladder,9,8

Ladder,9,9

2
What is the 29 doing in your file? - camickr
is your board initialized? - masotann
That is the number of the listed items on the file. - Erebus
Also, can we see your board 2d array declaration ? is it board[10][10]. - vishakvkt
Yes I initialized by board. - Erebus

2 Answers

0
votes

Replace s.nextInt(); with s.nextLine(); to read the first line from the file. If you need that value, you can do Integer.parseInt() on it.

0
votes

nextInt() doesn't change the line counter in Scanner, so nextLine() call will return the rest of the line you're currently at. To avoid that you need to explicitly change line counter by doing an extra nextLine() call after your nextInt():

s.nextInt();
s.nextLine();

From Scanner.nextLine API doc:

This method returns the rest of the current line, excluding any line separator at the end.

So in your code the first call to nextLine() simply returns an empty string.