dimanche 26 septembre 2021

Making a custom class using java.util.Random, keeps returning NullPointerException [duplicate]

I am a new student at a university learning how to code in Java. So far the assignments have been going fine, but I've encountered this odd error with my most recent one which I can't seem to find a fix for.

The assignment asks me to create my own class called MyRandom which allows the user to define a range containing a lower bound and an upper bound. The methods in the class will use this range to generate a completely random integer and double which must be located within the range. The tricky part is that the assignment has specified me to use speficially java.util.Random as an object variable to use for the methods. In Visual Studio the code does not seem to display any errors, yet when I attempt to run it in a test client I receive a java.lang.NullPointerException which seems to start off at the method which is supposed to create a random whole number.

So far this is what I've got:

import java.util.Random;
public class MyRandom {

    //Object variables
    public Random randomGen;
    public int nextNumber;
    public double nextDecimal;
    public int lower;
    public int upper;

    public MyRandom(){ //The constructor MyRandom
    }
    

    

    public int nextNumber(int lower, int upper){ //Randomly generated whole number in range
        nextNumber = randomGen.nextInt(upper - lower) + lower;
        return nextNumber;
    }

    public double nextDecimal(double lower, double upper){ //Randomly generated decimal in range
        nextDecimal = randomGen.nextDouble()*(upper - lower) + lower;
        return nextDecimal;
    }
}   

Any help with this is really appreciated, as I am a bit lost on why it even gives me an exception when the code seems to be fine according to VS.




Aucun commentaire:

Enregistrer un commentaire