Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Random in java

 
xin wen
Ranch Hand
Posts: 64
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 280
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Try seeding the Random constructor first with the system time. This should give you the results you require.

Best Regards,
 
xin wen
Ranch Hand
Posts: 64
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks so much, it is working now!
 
Jason Kretzer
Ranch Hand
Posts: 280
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Glad I could help.
Best Regards,
 
Tom Blough
Ranch Hand
Posts: 263
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

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 ]
 
xin wen
Ranch Hand
Posts: 64
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks you guys so much for helping me, thanks a lot!
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic