aspose file tools*
The moose likes Beginning Java and the fly likes Random in java Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Spring in Action this week in the Spring forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Random in java" Watch "Random in java" New topic
Author

Random in java

xin wen
Ranch Hand

Joined: Oct 11, 2002
Posts: 64
Hi there,
I am using Random to generate 3 numbers one time, and I will call it 100 times, but when I ran the program again, these numbers did not change. For example:
Fist 100 times:
1 4 6
2 6 8
3 6 9
: : :
: : :
: : :
Run again still:
1 4 6
2 6 8
3 5 9
: : :
: : :
: : :
Since it is Random select, they suppose to be different every time right?
private static Random m_r = new Random();
v_stop = m_r.nextInt(50);
Does anyone know why this happened?
Thanks a lot
Jason Kretzer
Ranch Hand

Joined: May 31, 2001
Posts: 280
Try seeding the Random constructor first with the system time. This should give you the results you require.

Best Regards,


Jason R. Kretzer<br />Software Engineer<br />System Administrator<br /><a href="http://alia.iwarp.com" target="_blank" rel="nofollow">http://alia.iwarp.com</a>
xin wen
Ranch Hand

Joined: Oct 11, 2002
Posts: 64
Thanks so much, it is working now!
Jason Kretzer
Ranch Hand

Joined: May 31, 2001
Posts: 280
Glad I could help.
Best Regards,
Tom Blough
Ranch Hand

Joined: Jul 31, 2003
Posts: 263

Random
public Random()Creates a new random number generator. Its seed is initialized to a value based on the current time:
public Random() { this(System.currentTimeMillis()); }Two Random objects created within the same millisecond will have the same sequence of random numbers.
See Also:
System.currentTimeMillis()

According to the Java documentation, calling new Random() SHOULD seed the generator with the current time automatically.
[ edited to change the code block to a quote block, in order to break apart big, long, unbroken, preformatted lines that require horizontal scrolling -ds ]
[ October 17, 2003: Message edited by: Dirk Schreckmann ]

Tom Blough<br /> <blockquote><font size="1" face="Verdana, Arial">quote:</font><hr>Cum catapultae proscriptae erunt tum soli proscripti catapultas habebunt.<hr></blockquote>
xin wen
Ranch Hand

Joined: Oct 11, 2002
Posts: 64
Thanks you guys so much for helping me, thanks a lot!
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Random in java