I'm trying to add a string to a 2d array, maze. It compiles, but when I run it it gives "Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 3" even though the dimensionY is set to 4.
public static void main(String[] args) throws IOException
{
List<String> lines = Files.readAllLines(Paths.get("C:\\Users\\zarga\\OneDrive\\Documents\\HW\\CSIS139\\MazeSolver\\src\\maze.txt"));
// now print out what the text file has in a for loop.
for (String line : lines)
{
System.out.println(line);
}
String line = lines.toString();
System.out.println();
System.out.println("Dimensions: " + Dimensions1(lines) + " by " + Dimensions2(lines));
System.out.println("Start position y: " + getEndCoordinateY(line));
System.out.println("Start position x: " + getEndCoordinateX(line));
char[][] mazeArray = new char[Dimensions1(lines)][Dimensions2(lines)];
mazeArray = mazeCreator(lines, mazeArray );
}
//get first number in dimension
public static int Dimensions1(List<String> list)
{
String firstLine = "";
String stringList = list.toString();
for (int i = 1; i <= 3; i++)
{
firstLine = firstLine + stringList.charAt(i);
}
int firstDim = Integer.parseInt(firstLine);
return firstDim;
}
//get second number in the dimension
public static int Dimensions2(List<String> list)
{
String firstLine = "";
String stringList = list.toString();
for (int i = 5; i <= 7; i++)
{
firstLine = firstLine + stringList.charAt(i);
}
int secondDim = Integer.parseInt(firstLine);
return secondDim;
}
//get ending coordinate Y position
public static int getEndCoordinateY (String list)
{
String lastLine = "";
String stringList = list;
int startY = 0;
int length = list.length();
for(int i = length - 2; i > (length - 5); i--)
{
lastLine = stringList.charAt(i) + lastLine;
}
startY = Integer.parseInt(lastLine);
return startY;
}
//get ending coordinate X position
public static int getEndCoordinateX (String list)
{
String lastLine = "";
String stringList = list;
int startX = 0;
int length = list.length();
for(int i = length - 6; i > (stringList.length() - 9); i--)
{
lastLine = stringList.charAt(i) + lastLine;
}
startX = Integer.parseInt(lastLine);
return startX;
}
//create the maze
public static char[][] mazeCreator (List<String> list, char maze[][])
{
int dimensionX = Dimensions1(list);
int dimensionY = Dimensions2(list);
String lines = "";
String stringList = list.toString();
for(int i = 8; i <= stringList.length() - 18; i++)
{
if(stringList.charAt(i) == ',' || stringList.charAt(i) == ' ')
{
//do nothing to get rid of all ,'s or spaces
}
else
{
lines = lines + stringList.charAt(i);
}
}
System.out.println(lines);
int offset = 0;
for(int x = 0; x < dimensionX; x++)
{
for(int y = 0; y < dimensionY; y++)
{
maze[x][y] = lines.charAt(offset++);
}
}
System.out.println(maze);
return maze;
}
}
I've printed Dimensions1(lines) and Dimensions2(lines) and both come out to 4. So the dimensions should be 4 by 4, but for some reason it runs out of bounds at 3.