Generate random doubles in between a range of valu

2019-09-07 01:51发布

问题:

I have written this piece of code which generates random doubles in between -1 and 1. The only problem is that it only produces one random double and then just prints out that for the other doubles that I want to produce. E.g. if the first double is 0.51 it just prints 0.51 over and over again instead of generating new random doubles.

What is wrong with the following code?

public static void main(String[] args) {
    double start = -1;
    double end = 1;
    double random = new Random().nextDouble();

    for(int i=1; i<10; i++){
        double result = start + (random * (end - start));

        System.out.println(result);
    }
}

Thanks in advance!

回答1:

You must generate new random (nextDouble()) each time you want a new random number. Try:

public static void main(String[] args) {
    double start = -1;
    double end = 1;
    Random random = new Random();

    for(int i=1; i<10; i++){
        double result = start + (random.nextDouble() * (end - start));

        System.out.println(result);
    }
}