简体   繁体   English

J2ME:如何生成随机数?

[英]J2ME: How to generate random number?

I just wanted to know how do I generate random number using J2ME CLDC 1.0 MIDP 2.0 ? 我只是想知道如何使用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. 基本上我想在每次从手机屏幕点击菜单项Generate时生成一个14位的随机数。

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: 我对J2ME并不熟悉,但Javadoc显示Random类是CLDC api的一部分,因此您可以生成一个14位数字,如下所示:

public static void main(String[] args) {
    Random r = new Random();
    long l = r.nextLong();
    System.out.println(String.format("%015d", l).substring(1, 15));
}
Random r = new Random();
r.nextInt(bottomX-topX)+topX; //will give you the next random integer in range [bottomX,topX]

You can use the Random class of MIDP, or the one in CLDC 1.1 您可以使用MIDP的Random类或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. 您可以执行nextLong然后截断,或使用next(44)并从那里迭代以获得真正的14个数字长。

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. 您可以使用此通用方法计算任何范围内的随机数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM