Random Numbers (Argh!)

Hi everybody!

I haven't used random numbers that often in Java and today I was trying to use them. I'm making a program generates many random numbers and holds on to them for later reference. My strategy was to create an array of the Random class by using a for loop, then store those random numbers to double variables like such.

Random[] rand = new Random[str.length()];

double[] val = new double[str.length()];

for (int x = 1; x < str.length(); x++) {

rand[x] = new Random();

val[x] = rand[x].nextDouble();

}

Now I did this, and to my surprise <insert haunting music here> all the numbers popped up the same! I'm learning / have learned Java from Sam's Teach Yourself Java 2. That book kind of touches on random numbers and how they are really "pseudo-random", and I understand that and all, but it never tells how to get around the "pseudo-randomness". I'm guessing that my problem is that Java works it's magic so fast that all the numbers are generated at virtually the same instant.

I have tried to make the numbers different by inserting a pointless time wasting loop inside the for loop but I don't want it to take forever. I tried inserting the variable x as a seed in the 5th line. Nothing worked that well. Any ideas? HAve I overlooked the simple solution?

Thans a million!

~Matt

[1405 byte] By [zhentilar5] at [2007-9-26 2:59:15]
# 1

You are using a new instance of Random for each loop iteration (with the same - default seed), so val[x] is bound to contain the same answer. Try this:

Random rand = new Random(System.currentTimeMillis());// this will make your array different each time you run

double[] val = new double[str.length()];

for (int x = 0; x < str.length(); x++) {

val[x] = rand.nextDouble();

}

Also note - Java arrays start with an index of 0, not 1

rob_canoe2 at 2007-6-29 10:55:06 > top of Java-index,Archived Forums,Java Programming...
# 2
Hi Rob_canoe2!Tell me please how did you insert preformatted text in your posting? I tried to write <pre> and </pre> but after posting it was converted to HTML, something like: &.lt;pre&.gt; and so on.Regards,Martin
edosoft at 2007-6-29 10:55:06 > top of Java-index,Archived Forums,Java Programming...
# 3
http://forum.java.sun.com/faq.jsp#messageformat use [code] [/code]
rob_canoe2 at 2007-6-29 10:55:06 > top of Java-index,Archived Forums,Java Programming...
# 4
<<Also note - Java arrays start with an index of 0, not 1 >>Oops... hehe. I knew that, but it didn't directly copy my program into the message. That's why I put 1. Thanks though.~Matt
zhentilar5 at 2007-6-29 10:55:06 > top of Java-index,Archived Forums,Java Programming...