How to generate Random Numbers in J2ME application

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

This blog is protected by dr Dave\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\'s Spam Karma 2: 141447 Spams eaten and counting...