Extreme Java When vanilla Java is not enough

5Sep/081

Random numbers in JavaME (and JavaSE)

In the absence of a Math.random() method in JavaME, you can use the java.util.Random class to do the job:

Random random = new Random(System.currentTimeMillis());
// JavaSE and CDLC 1.1
float f = random.nextFloat(); [0; 1[
// JavaSE and CDLC 1.0
int a = random.nextInt(); // [0; *[
int b = random.nextInt(20); // [0; 20[
int n = random.nextInt(max - min + 1) + min; // [min; max]

This tip can be used on JavaSE, if you want to generate a random number between "min" and "max". It is easier than multiplying and casting to integer.

Tagged as: , 1 Comment