如何创建一个特定首位数字的随机16位数?

8
我想在Java中创建一个随机生成的16位数字。但是需要注意的是,我需要前两个数字为"52"。例如:5289-7894-2435-1967。
我考虑使用随机生成器生成一个14位数字,然后再添加一个整数5200000000000000。
我试着寻找类似的问题,但没有找到有用的东西。我对数学方法不熟悉,也许它可以帮我解决问题。

4
生成(伪)随机数。在它前面加上“52”? - matcheek
一个谷歌搜索。有了这个,其余的就很容易了。https://dev59.com/M3A65IYBdhLWcg3wogSe - austin wernli
是的,我也有这个想法,但我不知道该怎么做。这就是我的问题所在。 - Marios Ath
你可能应该看一下这两个链接:https://dev59.com/cG445IYBdhLWcg3w499ehttps://dev59.com/oW435IYBdhLWcg3wlRIf - user1676389
你的想法是随机生成一个14位数,然后加上5200000000000000(或将其转换为字符串并在前面添加“52”),这是有道理的。你是否关心是否能够生成每个可能的14位数,或者如果你的随机数生成器错过了一些可能性,这是否可以接受?你是否关心分布的均匀程度? - ajb
或者谷歌搜索“生成随机万事达卡号” - Icemanind
4个回答

8
首先,您需要生成一个随机的14位数字,就像您已经做过的一样:
long first14 = (long) (Math.random() * 100000000000000L);

然后在开头添加52
long number = 5200000000000000L + first14;

另一种同样有效且可以节省内存的方法是使用 Math.random() 创建一个内部的 Random 对象:

//Declare this before you need to use it
java.util.Random rng = new java.util.Random(); //Provide a seed if you want the same ones every time
...
//Then, when you need a number:
long first14 = (rng.nextLong() % 100000000000000L) + 5200000000000000L;
//Or, to mimic the Math.random() option
long first14 = (rng.nextDouble() * 100000000000000L) + 5200000000000000L;

请注意,nextLong() % n 不会像Math.random()一样提供完全随机的分布。但是,如果您只是生成测试数据并且不必具有密码学安全性,则同样有效。使用哪个取决于您。

3
你可以生成14个随机数字,然后在开头添加 "52"。例如:
public class Tes {

    public static void main(String[] args) {
        System.out.println(generateRandom(52));
    }

    public static long generateRandom(int prefix) {
        Random rand = new Random();

        long x = (long)(rand.nextDouble()*100000000000000L);

        String s = String.valueOf(prefix) + String.format("%014d", x);
        return Long.valueOf(s);
    }
}

如果您不想使用String处理来添加数字,也可以通过将5200000000000000(加减一些零)加到x上来添加52。对我来说,这种方法更简洁。 - anon
实际上,你发布的使用String添加前缀的代码是错误的。如果x小于10 ^ 13,它将失败。你需要像这样编写:String.format("%014d", x) - ajb
(long)(rand.nextDouble()*100000000000000L)的数字均匀分布吗?最好使用这个链接:https://dev59.com/xXE85IYBdhLWcg3w64EA#2546186 - xehpuk

3
Random rand = new Random();
String yourValue = String.format((Locale)null, //don't want any thousand separators
                        "52%02d-%04d-%04d-%04d",
                        rand.nextInt(100),
                        rand.nextInt(10000),
                        rand.nextInt(10000),
                        rand.nextInt(10000));

0
  • 使用Math.random创建一个14位的随机数字。
  • 在开头连接字符串"52"。
  • Integer.parseInt(String)方法将字符串转换为整数。

很遗憾,您没有解释如何执行第一步。 这并不是微不足道的,因为 Random.nextLong() 不允许您指定一个界限,就像 Random.nextInt(bound) 一样。 - ajb

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接