给定长度的Java随机数 [英] Java random number with given length

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

问题描述

我需要在 Java 中生成一个 6 位数的随机数.我知道我可以在 randomicer 上循环 6 次,但是在标准 Java SE 中还有其他方法可以做到这一点吗?

I need to genarate a random number with exactly 6 digits in Java. I know i could loop 6 times over a randomicer but is there a nother way to do this in the standard Java SE ?

编辑 - 跟进问题:

现在我可以生成我的 6 位数字,我遇到了一个新问题,我尝试创建的整个 ID 的语法为 123456-A1B45.那么我如何随机化最后 5 个可以是 A-Z 或 0-9 的字符?我正在考虑使用 char 值并随机分配一个 48 - 90 之间的数字,然后简单地删除任何代表 58-64 的数字的值.这是要走的路还是有更好的解决方案?

Now that I can generate my 6 digits i got a new problem, the whole ID I'm trying to create is of the syntax 123456-A1B45. So how do i randomice the last 5 chars that can be either A-Z or 0-9? I'm thinking of using the char value and randomice a number between 48 - 90 and simply drop any value that gets the numbers that represent 58-64. Is this the way to go or is there a better solution?

编辑 2:

这是我的最终解决方案.感谢大家的帮助!

This is my final solution. Thanks for all the help guys!

protected String createRandomRegistryId(String handleId)
{
    // syntax we would like to generate is DIA123456-A1B34      
    String val = "DI";      

    // char (1), random A-Z
    int ranChar = 65 + (new Random()).nextInt(90-65);
    char ch = (char)ranChar;        
    val += ch;      

    // numbers (6), random 0-9
    Random r = new Random();
    int numbers = 100000 + (int)(r.nextFloat() * 899900);
    val += String.valueOf(numbers);

    val += "-";
    // char or numbers (5), random 0-9 A-Z
    for(int i = 0; i<6;){
        int ranAny = 48 + (new Random()).nextInt(90-65);

        if(!(57 < ranAny && ranAny<= 65)){
        char c = (char)ranAny;      
        val += c;
        i++;
        }

    }

    return val;
}

推荐答案

生成100000999999范围内的数字.

// pseudo code
int n = 100000 + random_float() * 900000;

有关更多详细信息,请参阅 Random<的文档/a>

For more details see the documentation for Random

这篇关于给定长度的Java随机数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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