Hunter Simon Hunter Simon - 3 years ago 135
Java Question

I can't print an array grid with objects and my class? Netbeans w/ Java

I am making a grid with the amounts determined by a scanner. I keep getting an error and I am not sure why. Here is the code for the grid that I am trying to make, I will also include the object and class for the maze/grid below.

public static void mazeSetup() {
System.out.println("How many rows and columns do you want? I would\n"
+ "suggest 10 minimum and 20 maximum.");
boolean mazeselect = true;
while(mazeselect) {
maze.columns = sc.nextInt();
maze.rows = maze.columns;
if (maze.rows > 30 || maze.rows < 10) {
System.out.println("Make sure that you make it within 10-30 rows.");
} else {
mazeselect = false;
}
}
mazeBuild();
}

public static void mazeBuild() {
for(int x = 0; x < maze.rows; x++) {
for(int y = 0; y < maze.columns; y++) {
maze.maze[x][y]= ".";
System.out.print(maze.maze[x][y]);
}
System.out.println();
}
characterPlacement();


}

I also have the object here:

static Maze maze = new Maze(null,0,0,0,0);


and the class with construtors for the maze/grid.

public class Maze {

String maze[][];
int rows;
int columns;
int xStart;
int yStart;

public Maze(String xMaze[][], int xRows, int xColumns, int xxStart, int xyStart) {
maze = xMaze;
rows = xRows;
columns = xColumns;
xStart = xxStart;
yStart = xyStart;
}
public String[][] maze() {
return maze;
}
public int rows() {
return rows;
}
public int columns() {
return columns;
}
public int xStart() {
return xStart;
}
public int yStart() {
return yStart;
}


}

Any help would be greatly appreciated. Thanks a lot! :D

Note: No errors occur until ran in console.

Answer Source

your String maze[][] is null because of this:

static Maze maze = new Maze(null,0,0,0,0); // notice that null

And you're trying to put values in it upon calling mazeBuild(). You should initialize it or pass an array instead of null. You can do this at the start of mazeBuild()

public static void mazeBuild() {
    maze.maze = new String[maze.rows][maze.columns]; // <-- this one!

    for(int x = 0; x < maze.rows; x++) { // <-- this loop tries to
        for(int y = 0; y < maze.columns; y++) { // put values in your
            maze.maze[x][y]= ".";               // maze.maze (2D String array)
            System.out.print(maze.maze[x][y]);
    }
    System.out.println();
}

You can also do this in exchange to the line of code I've added.

String[][] mazeArray = new String[maze.rows][maze.columns];
maze = new Maze(mazeArray, maze.rows, maze.columns, 0, 0);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download