Generate random doubles in between a range of values - Java

流过昼夜 提交于 2019-12-11 19:35:34

问题


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);
    }
}


来源:https://stackoverflow.com/questions/21307702/generate-random-doubles-in-between-a-range-of-values-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!