3

I just wanted to know how do I generate random number using J2ME CLDC 1.0 MIDP 2.0 ?

Basically I want to generate a 14 digits random number each time when the menu item Generate is clicked from the mobile's screen.

gnat
  • 6,213
  • 108
  • 53
  • 73
Sarfraz
  • 377,238
  • 77
  • 533
  • 578

4 Answers4

3

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));
}
Jared Russell
  • 10,804
  • 6
  • 30
  • 31
  • I think this would be less random...Two random long can have the same first 14 characters and not be equals. – Valentin Rocher Jan 16 '10 at 11:42
  • 2
    It would only be "less random" if you did the opposite, i.e. try to generate a 14 digit number from a source that has lass than 10^14 possible values. The code above has a different problem: it will result in a StringIndexOutOfBoundsException when the random long has less than 14 digits. – Michael Borgwardt Jan 16 '10 at 11:51
  • Ah, I missed that. I've corrected it to deal with numbers less than 14 digits in length. One other problem with the code I posted was that it would have negative numbers, this has also been fixed. – Jared Russell Jan 16 '10 at 12:09
2
Random r = new Random();
r.nextInt(bottomX-topX)+topX; //will give you the next random integer in range [bottomX,topX]
Vitali Pom
  • 602
  • 1
  • 8
  • 29
1

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.

Valentin Rocher
  • 11,667
  • 45
  • 59
0
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.

Vivart
  • 14,900
  • 6
  • 36
  • 74