I'm trying to get a random integer, but the way I'm doing it takes a really long time to get that random number ( like 10 seconds!)
Random generator=new Random();
do {
id=generator.nextInt();
}
while(id<=0||id>=4);
I'm trying to get a random number between (and include) 0 to 4 This code so far gets the job done, but 10 seconds is too long!
what is a better way to do this?
Thanks!
You want
generator.nextInt(5);
which returns a random integer between 0 and 4. The reason why your original code took so long was because it was generating random integers over and over, until it got one between 1 and 3.
Note that as you were throwing away everything 0 or less, and everything 4 or more, you weren't even getting the range that you expected.
More information on the methods of the Random
class can be found at http://docs.oracle.com/javase/7/docs/api/java/util/Random.html
That's because you're generating literally probably billions of random numbers and throwing them away until you get one between 0 and 4. Instead:
id = generator.nextInt(5); // number between 0 and 4, inclusive
In the future, please read the documentation for the classes you're using; this is clearly explained in the Javadoc .
使用Math.random( )将其强制转换为int
int i=(int)Math.random()*4;
Just include the upper bound (assuming you want 1, 2, or 3):
id = 1 + generator.nextInt(3);
From the javadoc :
public int nextInt(int n)
Returns a pseudorandom, uniformly distributed int value between 0 (inclusive) and the specified value (exclusive), drawn from this random number generator's sequence.
try this:
Random random = new Random();
random.nextInt(4);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.