0

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!

Mr. P
  • 1,387
  • 1
  • 11
  • 25
user3146858
  • 55
  • 2
  • 8

1 Answers1

2

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);
    }
}
Mr. P
  • 1,387
  • 1
  • 11
  • 25
  • Hi, thanks for this! I changed it to now say nextDouble but now it says that I cannot invoke nextDouble on the primitive type double. I had a look online and it said that nextDouble can only be used on random and scanner, which is what I am doing. Would you know the cause of this? Thanks again :) – user3146858 Jan 23 '14 at 12:22
  • @user3146858, Have a look at my code - i am executing nextDouble() on Random object, not on double primitive. Random is an object for generating pseudo-random data. You have many methods in this class for generating int's, doubles etc. Consider revising http://docs.oracle.com/javase/6/docs/api/java/util/Random.html – Mr. P Jan 23 '14 at 12:27
  • Just remember it is a pseudo-random. There are ways to generate some particular sets like for example `nextInt` will return `1` ten times in a row etc. – Mr. P Jan 23 '14 at 12:30
  • 2
    Generating 1 ten times in a row is by no means an indication that the sequence is pseudorandom. The fact that the sequence is *deterministically reproducible*---is. – Marko Topolnik Jan 23 '14 at 12:55