Null Pointer Exception when writing to arrays

edited June 2017 in Questions about Code

I am using some code that generates an empty array of custom objects (which don't have a traditional constructor) that use a method to initialize all values; every time I run a method, or write to a value in the creature I get a null pointer exception.
Code:
Creature Class
class Creature{ public int x, y, i = 0; public int[] move = new int[50]; public void init(int xi, int yi, int[] movei){ x = xi; y = yi; i = 1; move = movei; } public void render(){ ellipse(x, y, 5, 5); } private void set(int a, int b){ x = a; y = b; } public void generate(){ for(int a = 0; a < move.length; a++){ this.move[a] = int(random(1, 4)); } this.x = width/2; this.y = height/2; this.i = 0; } private void bread(){ for(int a = 0; a < 0; a++){ if(int(random(1, 5)) == 5){ move[a] = int(random(1,4)); } } i = 0; } public boolean tick(){ if(i < move.length){ switch(move[i]){ case 1: set(x, y-1);break; case 2: set(x, y+1);break; case 3: set(x-1, y);break; case 4: set(x+1, y);break; default: break; } i++; return false; }else{ bread(); return true; } } public Creature clone(){ Creature a = this; a.x = width/2; a.y = height/2; a.i = 0; return a; } }
in the main part I just use
Creature[] a = new Creature[50];
and try to call methods on objects in the array

Tagged:

Answers

  • Creature[] a = new Creature[50];

    just creates an array that can hold 50 Creature(s) it DOES NOT create the actual creatures.

    Create the Creature objects in setup with

    for(int i = 0; i < a.length; i++){
      a[i] = new Creature();
    }
    
Sign In or Register to comment.