ads

How to generate Random Numbers in J2ME application

September 28th, 2007 5 Comments   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,