Hi,
I just wanted to know how do I generate random number using J2ME?
Basically i want to generate a 14 digits random number each time when the menu item Generate is clicked from the mobile's screen.
Thanks
Hi,
I just wanted to know how do I generate random number using J2ME?
Basically i want to generate a 14 digits random number each time when the menu item Generate is clicked from the mobile's screen.
Thanks
You can use the Random class of MIDP, or the one in CLDC 1.1
You could do nextLong
and then truncate, or use next(44) and iterate from there to have a real 14-number long.
I'm not really familiar with J2ME, however the Javadoc shows that the Random class is part of the CLDC api, so you can generate a 14 digit number like this:
public static void main(String[] args) {
Random r = new Random();
long l = r.nextLong();
System.out.println(String.format("%015d", l).substring(1, 15));
}
import java.util.Random;
private static void showRandomInteger(int aStart, int aEnd){
Random generator = new Random();
generator.setSeed(System.currentTimeMillis());
if ( aStart > aEnd ) {
throw new IllegalArgumentException("Start cannot exceed End.");
}
//get the range, casting to long to avoid overflow problems
long range = (long)aEnd - (long)aStart + 1;
// compute a fraction of the range, 0 <= frac < range
long fraction = (long)(range * generator.nextDouble());
int randomNumber = (int)(fraction + aStart);
System.out.println("Generated : " + randomNumber);
}
you can use this general method for calculating random numbers in any range.