Why do I get a NullPointerException when I use Random.nextGaussian() ???

edited October 2013 in Questions about Code

I made this simple program to illustrate my problem (that I have in a bigger program).

I try to create an ArrayList with different elements by using a function in the constructor of those elements to set a specific (random) value.

This works fine if I use random() or if I create my own random generator, but not when I use the imported Random Class. Why is this? and how can I make it work?

import java.util.Random;

// Two Classes to generate a number (gen and rand) and one to generate a list (lis)
NumberGenerator  gen;
Random           rand;
ListGenerator    lis;

public void setup(){
  gen  = new NumberGenerator();
  lis = new ListGenerator();
  rand = new Random();
}

// We print the random numbers in the list
public void draw(){
  for(int i = 0; i < lis.numberList.size(); i++){
    print(lis.numberList.get(i).value + " ");
  }
  println();
}

// This is a simple number generator
public class NumberGenerator{
  float generateNumber(){
    return random(1000);
  } 
}

// Here we generate the random numbers with the use of the class (Number)
public class ListGenerator{
  ArrayList<Number> numberList;

  public ListGenerator(){
    numberList = new ArrayList<Number>();
    for(int i = 0; i < 10; i++){
       numberList.add(new Number());
    }
  }
}

public class Number{
  float value;

  public Number(){
    value = gen.generateNumber();
    //value = (float)rand.nextGaussian();
  }
}

Answers

  • Answer ✓

    The reason is that the ListGenerator constructor (line 10) calls the Number class constructor (line 26) which attempts to call rand.nextGaussian, but the rand object has not been created yet because line 11 has not been executed.

    Change setup to

    public void setup(){
      rand = new Random();
      gen  = new NumberGenerator();
      lis = new ListGenerator();
    }
    

    and it works a treat.

  • Thanks,

    It works! (also in my real program).

    Learned something new today :-)

Sign In or Register to comment.