具有给定长度的Java随机数 [英] Java random number with given length
问题描述
我需要在Java中使用正好6位的随机数进行生成。我知道我可以在随机数上循环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值和randomice一个介于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;
}
推荐答案
生成范围内的数字从 100000
到 999999
。
Generate a number in the range from 100000
to 999999
.
// pseudo code
int n = 100000 + random_float() * 900000;
我很确定你已经阅读过例如随机,可以自己弄清楚其余部分。
I’m pretty sure you have already read the documentation for e.g. Random and can figure out the rest yourself.
这篇关于具有给定长度的Java随机数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!