Null Pointer exception

edited February 2015 in Questions about Code

Whenever I try to run this I get the addObstacle function I get a NullPointerException error. Please help.

ArrayList<Level> levels;

class Level{

  ArrayList<Obstacle> obstacles;

  Level(){
  }

  void load(){
  }

  void addObstacle (float x1 , float y1 , float x2 , float y2 , int t){
    obstacles.add (new Obstacle (x1 , y1, x2 , y2, t));
  }
}

Comments

  • Can you put up the Obstacle class? We don't really know what you're doing in there.

  • i don't think we need that tbh.

    line 5 is not enough to create an ArrayList. you need to assign the result of new ArrayList(); to it somewhere (maybe even line 5 itself)

  • edited February 2015
    // forum.processing.org/two/discussion/9538/null-pointer-exception
    
    import java.util.List;
    
    class Level {
      final List<Obstacle> obstacles = new ArrayList<Obstacle>();
    
      void addObstacle(float x1, float y1, float x2, float y2, int t) {
        obstacles.add(new Obstacle(x1, y1, x2, y2, t));
      }
    }
    
    class Obstacle {
      float x1, y1, x2, y2;
      int t;
    
      Obstacle(float $x1, float $y1, float $x2, float $y2, int $t) {
        x1 = $x1;
        y1 = $y1;
        x2 = $x2;
        y2 = $y2;
        t = $t;
      }
    }
    
Sign In or Register to comment.