views:

712

answers:

3

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

+1  A: 

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
14 digits will overflow the int variable.
jarnbjo
omg, what a newb error :/changed it to a long
Valentin Rocher
And I don't believe you intend to use the parameterless nextInt() method...
Michael Borgwardt
I removed my code, it was quickly-coded (and non-tested) bullshit...I'll just give him some advice.
Valentin Rocher
`next(int)` returns an int, the argument can't be larger than 32. That's by the way also what the linked docs tell you.
Joey
+2  A: 

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
I think this would be less random...Two random long can have the same first 14 characters and not be equals.
Valentin Rocher
less random than what?
GregS
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
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
+1  A: 
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
`nextDouble()` is not accessible in the J2ME version of random
Valentin Rocher
yes its not there in cldc 1.0 but you can find in cldc 1.1
Vivart
but i am using cldc 1.0, what for that?
Sarfraz