如何生成随机的五位数Java [英] How to generate a random five digit number Java

查看:2905
本文介绍了如何生成随机的五位数Java的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能重复:

Java:生成范围内的随机数

我需要一些帮助。

我会使用什么代码创建一个长度为5位且以1或2开头的随机数?

What code would I use to create a random number that is 5 digits long and starts with either 1 or 2?

以公司员工身份用作身份。

in order to use as a company employees ID.

谢谢!!

推荐答案

取决于你如何解决这个问题:

Depending on how you approach the problem something like that:

public int gen() {
    Random r = new Random( System.currentTimeMillis() );
    return 10000 + r.nextInt(20000);
}

或类似的东西(你可能想要随机的瞬间该方法的对象,但为了简单起见,我只是把它放在这里):

Or something like that (you probably want the instantation of the Random object of of the method but I just put it here for simplicity) :

public int gen() {
    Random r = new Random( System.currentTimeMillis() );
    return ((1 + r.nextInt(2)) * 10000 + r.nextInt(10000));
}

想法是 1 + nextInt(2)应始终给出1或2.然后将它乘以10000以满足您的要求,然后在[0..9999]之间添加一个数字。

The idea is that 1 + nextInt(2) shall always give 1 or 2. You then multiply it by 10000 to satisfy your requirement and then add a number between [0..9999].

这是一些例子输出:

14499
12713
14192
13381
14501
24695
18802
25942
21558
26100
29350
23976
29045
16170
23200
23098
20465
23284
16035
18628

这篇关于如何生成随机的五位数Java的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆