Question

I know there's been a lot of questions on Seeds here before already, I've looked through quite a few but am still struggling, sorry if this seems repetitive! Basically I'm prompting the user for an input value (which will be the seed) and then using that seed to generate random values. My code is in two separate files, but I'll try to keep this organized for you.

File 1:

Random generator = new Random();

public RandomWalk(int gridSize){

    gridSize = generator.nextInt();
    this.gridSize = gridSize;
}



public RandomWalk(int gridSize, long seed){
    generator.nextInt();
    this.gridSize = gridSize;
}

File 2:

public static long seed = 0;
int i = 1;
    System.out.println("Enter random seed (0 for no seed): ");
    while (i == 1) {
        seed = scan.nextInt();
        if (!(seed == 0)) {
            if (seed > 0) {
                i++;
                //Generate numbers based on seed entered
            } else {
                System.out.println("You need to enter a positive integer.");
            }
        } else {
            System.out.println("Seed is 0, a random seed will be generated");
            //Make this generate a random seed
            i++;
        }
    }

public static void main(String[] args) {

    getInput();

    RandomWalk walk;
    if (seed==0){
        walk = new RandomWalk(gridSize);
    } else {
        walk = new RandomWalk(gridSize, seed);
    }

    walk.createWalk();
Was it helpful?

Solution

You didn't really ask a question, but I'll try to infer it. Is it that your code is not working as you expected?

One issue I see is that your RandomWalk constructor which takes in a seed never does anything with the seed. Try this:

Random generator;

public RandomWalk(int gridSize){
    generator = new Random();
    gridSize = generator.nextInt();
    this.gridSize = gridSize;
}



public RandomWalk(int gridSize, long seed){
    generator = new Random(seed);
    gridSize = generator.nextInt();
    this.gridSize = gridSize;
}

Note that the seed is passed to the Random constructor. Additionally, your call to generator.nextInt() is made in the 2nd constructor without assigning its return value to gridSize. I think that may not have been what you intended to do.

You may want to take a look at the Java SDK documentation for Random. It has 2 constructors, one which accept a seed parameter and another which essentially makes one up for you.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top