开发者

Java Random: Seeding Problem

开发者 https://www.devze.com 2023-02-13 12:03 出处:网络
was wondering if you could help me out: I have a method called initializeAll: public final void initializeAll() {

was wondering if you could help me out:

I have a method called initializeAll:

public final void initializeAll() {
//other stuff........
rand = new Random(353);
}

So I run the project and a GUI pops up, and some operations are carried out. When I press the "reset" button in my GUI, intializeAll is called again on the same class object. However, the operations that are carried out now are not the same as before, although they should be, since both times, a seed of 353 is being used on the newly created Random object. Why this difference? Am I doing something wrong?

EDIT: sorry, its not "some operations are carried out". its that some initialization of agent population takes place. and each time, the initialization is different, although the same seed is used.

 开发者_运维知识库   private static int [][] initializePop(Random rand) {
        int[][] temp = new int[ROWS][COLS];
        for (int row = 0; row < ROWS; row++) {
            for (int col = 0; col < COLS; col++) {
                temp[row][col] = rand.nextInt(12) - 5;
            }
        }
        return temp;
    }

SOLUTION:

sorry for taking your time guys. i figured out the problem. right now, my application is a mess of various threads, swingworkers, etc i.e. very "thready".. apparently the random is actually working fine. the problem is with the GUI display, which does some funny things and displays some interesting value. so this is more of a threading problem. i'm redesigning the code now. so thanks again, and sorry for wasting your time.


Am I doing something wrong?

Yes, it seems so. The Random(long) should reset the seed to the provided value. What ever the error is, it will be impossible for us to help you without an SSCCE or at least more code.

Random rand = new Random(353);
System.out.println(rand.nextInt(10));
System.out.println(rand.nextInt(10));
System.out.println(rand.nextInt(10));

rand = new Random(353);
System.out.println(rand.nextInt(10));
System.out.println(rand.nextInt(10));
System.out.println(rand.nextInt(10));

Output:

7
5
5
7
5
5


sorry for taking your time guys. i figured out the problem. right now, my application is a mess of various threads, swingworkers, etc i.e. very "thready".. apparently the random is actually working fine. the problem is with the GUI display, which does some funny things and displays some interesting value. so this is more of a threading problem. so thanks again, and sorry for wasting your time.

0

精彩评论

暂无评论...
验证码 换一张
取 消