ThinkGeek - Cool Stuff for Geeks and Technophiles

December 01, 2004

[J2ME]: Random class

Have you ever worked as part of a team where all the other developers are Java experts? How many times have you heard "Flash is very strange, there are a lot of quirks"?.

Well, Java also has its own quirks, like, for instance the Random class. Maybe this is obvious for all the experienced J2ME developers out there, but it took me almost an hour of my work to notice that the Random class ( java.util.Random ) that is part of the MIDP 1.0 is different from the "standard" J2EE Random class.

And the difference ( and my problem ) came because although there is a nextInt( ) method, there's not a nextInt( int i ) method in the J2ME class.

So, what if I need to generate a random number smaller than a given value?.

Easy:

Random random = new Random( );
int randomNumber = Math.abs( random.nextInt() % UPPER_LIMIT );

where UPPER_LIMIT is a constant, whose value is the upper limit of the random value.

Posted by Cesar Tardaguila Date: December 1, 2004 10:53 PM | TrackBack
Comments

Isn't this the same as flash?

// as code:
var randomNumber = Math.abs( Math.random() % UPPER_LIMIT );

Posted by: david en: December 2, 2004 03:04 AM

Not really, in actionScript it should be:

var randomNumber: Number = Math.abs( Math.random( ) * UPPER_LIMIT);

Math.random( ) generates a random number between 0 and 1

Posted by: Cesar Tardaguila en: December 2, 2004 10:33 AM