-1

I have produced the following code but its execution produces a null pointer exception. For this reason I'm looking for some help.

I suppose that the exception is due to the pointer object but I can not understand what I 'm doing wrong. Here is my code:

import java.util.Random;
public class Maze {
  int width;
  int length;
  char elements[][];
  boolean visited[][] ;

  public Maze(int width,int length) {
    this.width=width;
    this.length=length;
    char elements[][] = new char[width][length];
    boolean visited[][] = new boolean[width][length];

    for(int i=1;i<length-1;i++){
        for(int j=1;j<width-1;j++){
            visited[i][j]=false;
        }
    }

    for(int i=0;i<length;i++){
        visited[0][i] = true;
        visited[width-1][i]=true;

    }

    for(int i=0;i<width;i++){
        visited[i][0]=true;
        visited[i][length-1]=true;
    }

    for(int i=0;i<width;i++){
        for(int j=0;j<length;j++){
            elements[i][j]='X';
        }
    }

  }

  public void generate(){
    Random rn = new Random();
    int start = rn.nextInt(length);
    int end = rn.nextInt(length);
    elements[0][start]='s';
    elements[width-1][end]='e';
    visited[1][start+1]=true;
    elements[1][start+1]=' ';

    for(int i=0;i<width;i++){
        for(int j=0;j<length;j++){
            System.out.println(elements[i][j]);
        }
    }
  }
}

public class MazeLauncher{
    public static void main(String args[]){
        Maze maze = new Maze(4,5);
        maze.generate();
    }
}
acornagl
  • 521
  • 5
  • 24
  • 1
    Please provide the NPE stack trace. – Grayson Oct 13 '16 at 14:46
  • 3
    Possible duplicate of [What is a NullPointerException, and how do I fix it?](http://stackoverflow.com/questions/218384/what-is-a-nullpointerexception-and-how-do-i-fix-it) – takendarkk Oct 13 '16 at 14:52
  • 1
    You don't have an object named "pointer". Please post the full error message so that we can find the problem easier. – Matt C Oct 13 '16 at 15:44

1 Answers1

0

Remove the declarations in your constructor.

public Maze(int width,int length) {
    this.width=width;
    this.length=length;
    elements = new char[width][length];
    visited = new boolean[width][length];
    ...
}

At the moment you are creating new arrays instead of using the already declared ones.

Turamarth
  • 2,282
  • 4
  • 25
  • 31