SlinkyMation SlinkyMation - 1 month ago 18
Java Question

Running Code after constructor in java?

I want to pass in the "seed" value into the constructor and then make a Random variable based on that seed value. I am not sure how to do this. Here is what I have going on:

public class Die
{

private int seed;
Random _randNum = new Random(seed);

public Die(int seed) { this.seed = seed; }
}


From the main class I am creating that "Die" variable like this:

private Die _die1 = new Die(5);


Basically, I want the "seed" value to be 5 when the

Random _randNum = new Random(seed);


is ran. Any ideas as to how to make this happen?

Answer

Change you code so that _randNum is instantiated in the constructor

e.g

public class Die
{
    private int seed;
    Random _randNum;

    public Die(int seed) { 
       this.seed = seed;  // actually no need to keep this value
       _randNum = new Random(seed);
    }
}
Comments