How to generate Random Numbers in J2ME application
September 28th, 2007 Posted in J2ME / JavaME, Java, newbie, Tips, Tricks, Guide
One of the popular question asked in this blog is ways to generate random numbers in J2ME application.
As most people probably realized, the JavaME CLDC does not include the Math.Random class to generate random numbers. However one can generate a series of random numbers in JavaME/J2ME application by using the included java.util.Random class.
Here’s a sample usage
import java.util.Random;
...
Random generator = new Random();
generator.setSeed(System.currentTimeMillis());
float f = generator.nextFloat();
System.out.println(""+(f*100.0f)%100);
...
The sample code above will produce a random floating-point number between 0..100 (exclusive)
Here’s the source code for the full Random Number Demo application : RandomDemo.java,
November 29th, 2007 at 4:39 pm
mbnmcvjkdj
August 20th, 2008 at 9:30 pm
There is no need to invoke setSeed after constructor because constructor does it!
April 7th, 2009 at 1:23 am
Yes thats it!!!
April 13th, 2009 at 10:56 am
I’ve analysed the numbers generated by J2me Random.NextFloat() with Arena’s Input Analyzer utilit in order to know if we can trust that the output data fit a uniformly distributed float value between 0.0 and 1.0. However, it seems that usually the sample fit the Beta Distribution. I’ve succesfull generated uniformly distributed sample by using .NextDouble() instead of .NextFloat().
July 31st, 2009 at 6:33 pm
very nice! thx!