0

I want the variables p and z to get a new random number assigned to them but I get a NullPointerException when using the code below. I've done something similar before and it worked fine so I am probably being silly and missing something obvious. Any help? Thanks!

example code:

private int p;
private int z;
private Random rand;

public test()
{
    p = 0;
    z = 0;
}

public void print()
{
    p = rand.nextInt(9);
    z = rand.nextInt(9);
    System.out.println(p + " " + z);
}

1 Answers1

8

You haven't initialized rand to anything yet, so Java initializes it to null, per JLS 4.12.5. Try

private Random rand = new Random();
rgettman
  • 176,041
  • 30
  • 275
  • 357