File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Beginning Java and the fly likes A question about java.util.Random Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "A question about java.util.Random" Watch "A question about java.util.Random" New topic

A question about java.util.Random

Peng Fan
Ranch Hand

Joined: May 04, 2004
Posts: 35
Why i got an array of constantly same value when i use a object of class Random to produce a series of randomly-generated value. By doing what I can avoid it? How does the class Random work behind scenes and what is the so-called seed. I am longing for your detailed explanation, please make it easy to understand since i am a novice. THX!
Barry Gaunt
Ranch Hand

Joined: Aug 03, 2002
Posts: 7729
Post your code and we'll see if we can help.

Ask a Meaningful Question and HowToAskQuestionsOnJavaRanch
Getting someone to think and try something out is much more useful than just telling them the answer.
Stefan Wagner
Ranch Hand

Joined: Jun 02, 2003
Posts: 1923

Since a random-generator generates it's values, they aren't as randomly as sometimes thought.

Modern systems use mouse- or keyboard-input, to generate numbers more randomly.

In most circumstances we don't need real random numbers, but something which looks like random.

Often there is a sequence of numbers generated, and this sequence is repeating itself, but after a very, very long time. A good algorithm will generate every possible value in the scope and with the same frequence.
The last generated number might be the start-value, to generate the next number, which leads to the same sequence for the same startvalue, the seed.

This looks like a drawback, but you may use a value based on the time to generate the seed, leading to new sequences for every run.
The same sequence might be very useful, when you compare two different implementations of an algorithm, which shall lead to the same result, but handle a lot of values, you don't like to generate manually.

Practical advice: Generate only one random = new Random () - object, and call (...) on this common Object, which leads to a sequence of values.
Peng Fan
Ranch Hand

Joined: May 04, 2004
Posts: 35

everytime when i try to run this bit of code, i got a array of int of 20 same values, but if i uncomment the line 1 and line 3 and comment line 2, i can get what i want. THX!
I agree. Here's the link:
subject: A question about java.util.Random
It's not a secret anymore!