jeudi 14 juillet 2016

Java Random.nextInt(int) return the same value when set different seed

I write a demo to test java.util.Random, but I get the same value when set different seeds.In my program, seeds range from 0 to 4. So I think the result will be groups of 4 different values. But the actual values output are all the same. What wrong with my codes? Could anyone tell me?

import java.util.Random;

public class Main {
    public Main() {
    }

    public static void main(String[] args) {
        for (int i = 0 ; i <= 255; i++)
        {
            String hex = Integer.toHexString(randInt(0, 255, i % 5));
            System.out.println(hex);
        }
    }
    private static Random rand = new Random();
    public static int randInt(int min, int max, long seed) {
        rand.setSeed(seed);
        System.out.println("seed:" + seed);
        int randomNum = rand.nextInt((max - min) + 1) + min;
        return randomNum;
    }
}

The result is :

seed:0
bb
seed:1
bb
seed:2
bb
seed:3
bb
seed:4
bb
seed:0
bb
seed:1
bb
seed:2
bb
seed:3
bb
seed:4
bb
seed:0
bb
seed:1
bb
seed:2
bb
seed:3
bb
seed:4
bb
seed:0
bb
seed:1
...
...
...




Aucun commentaire:

Enregistrer un commentaire