I'm currently trying to write a very simple program to test the capabilities of the "Random" class (java.util.Random) in a few ways, however I receive a Null Pointer Exception error when trying to run.
My code:
import java.util.Random;
public class RandomTester
{
public Random r;
public RandomTester()
{
Random r = new Random();
}
public void printOneRandom()
{
int s = 0;
s = r.nextInt(256); //NULL POINTER EXCEPTION HERE
System.out.println("Random 8-bit number: " + s);
}
public void printMultiRandom(int howMany)
{
for(int i=0 ; i<howMany ; i++)
{
System.out.println("Random 8-bit number: " + r.nextInt(256));
}
}
}
It works fine if I move the constructor from RandomTester() to either one of the methods but I was under the impression that writing it the above way should be okay. It may well just be I'm not quite grasping something fundamental or indeed that I should have instantiate the object elsewhere.
Thank you for any help, there's no main method shown as I'm using BlueJ (a learner IDE). It's also my first time exploring some of the basic classes.
Change this
Random r = new Random();
to
r = new Random();
You were previously initializing a different local variable that has a name that shadows your instance field. Your instance field was therefore initialized to a default value of null
.
When you tried to use it in one of your methods, it was still null
and gave you a NullPointException
when you tried to dereference it to invoke a method.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments