How to generate Random Numbers in J2ME application

September 28th, 2007 Posted in J2ME / JavaME, Java, Tips, Tricks, Guide, newbie

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

JAVA:
  1. import java.util.Random;
  2. ...
  3.     Random generator = new Random();
  4.     generator.setSeed(System.currentTimeMillis());
  5.     float f = generator.nextFloat();
  6.    
  7.     System.out.println(""+(f*100.0f)%100);
  8. ...

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,

 

Possibly Related Posts...

5 Responses to “How to generate Random Numbers in J2ME application”

  1. kien Says:

    mbnmcvjkdj



  2. S?awek Says:

    There is no need to invoke setSeed after constructor because constructor does it!



  3. Cesar Says:

    Yes thats it!!!



  4. Carlos B Says:

    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().



  5. Peter Peng Says:

    very nice! thx!



Leave a Reply