如何在Java中生成一个随机的9位数?
可能重复:如何在Java中生成一个随机的9位数?,java,random,cryptography,Java,Random,Cryptography,可能重复: 我需要生成一个9位数的唯一代码,就像产品背面用来识别它们的代码一样 代码应该是不重复的,并且数字之间应该没有相关性。代码也应该是所有整数 我需要使用java生成它们,同时将它们插入数据库。int noToCreate=1_000;//您需要的号码数 int noToCreate = 1_000; // the number of numbers you need Set<Integer> randomNumbers = new HashS
我需要生成一个9位数的唯一代码,就像产品背面用来识别它们的代码一样 代码应该是不重复的,并且数字之间应该没有相关性。代码也应该是所有整数 我需要使用java生成它们,同时将它们插入数据库。
int noToCreate=1_000;//您需要的号码数
int noToCreate = 1_000; // the number of numbers you need
Set<Integer> randomNumbers = new HashSet<>(noToCreate);
while (randomNumbers.size() < noToCreate) {
// number is only added if it does not exist
randomNumbers.add(ThreadLocalRandom.current().nextInt(100_000_000, 1_000_000_000));
}
Set randomNumbers=新哈希集(noToCreate);
while(randomNumbers.size()
生成一个9位随机数,并在数据库中查找唯一性
100000000 + random.nextInt(900000000)
或
我知道这样做有点奇怪,但我仍然认为你可以有你唯一的9位数字,几乎没有任何关系 询问你询问的
数字之间应该没有相关性
public class NumberGen {
public static void main(String[] args) {
long timeSeed = System.nanoTime(); // to get the current date time value
double randSeed = Math.random() * 1000; // random number generation
long midSeed = (long) (timeSeed * randSeed); // mixing up the time and
// rand number.
// variable timeSeed
// will be unique
// variable rand will
// ensure no relation
// between the numbers
String s = midSeed + "";
String subStr = s.substring(0, 9);
int finalSeed = Integer.parseInt(subStr); // integer value
System.out.println(finalSeed);
}
}
使用Commons Lang的
randomNumeric
方法:
)
不过,您必须对照数据库检查唯一性。嗯。。。如果你想的是条形码上的数字,这些数字并不完全是随机的,它们之间会有很强的相关性。它们是按时间链接的。这并不保证唯一性。请注意,数字格式中的下划线是自Java 1.7以来出现的一项功能。旧的源代码级别将不起作用。-1不使用安全随机function@owlstead要求不是使用安全的随机函数,所以我没有使用它,我看不出-1的理由,如果是这样的话,我道歉。如果你能指出这一要求,我很乐意投反对票(修正你的问题),我不确定我是否正确,但Prakash的要求是“代码应该是不重复的,它们之间应该没有数字的相关性。”-我不明白为什么在这种情况下使用ThreadLocalRandom是不够的。。。
100000000 + random.nextInt(900000000)