在Java中生成10位唯一的随机数

我正在尝试使用下面的代码来生成10位唯一的随机数。根据我的要求,我必须创建大约5000个唯一编号。这无法正常工作。它还会生成-

ve数字。同样,有时生成的数字中缺少一两位数字,导致8或9个数字而不是10。

public static synchronized  List generateRandomPin(){

int START =1000000000;

//int END = Integer.parseInt("9999999999");

//long END = Integer.parseInt("9999999999");

long END = 9999999999L;

Random random = new Random();

for (int idx = 1; idx <= 3000; ++idx){

createRandomInteger(START, END, random);

}

return null;

}

private static void createRandomInteger(int aStart, long aEnd, Random aRandom){

if ( aStart > aEnd ) {

throw new IllegalArgumentException("Start cannot exceed End.");

}

//get the range, casting to long to avoid overflow problems

long range = (long)aEnd - (long)aStart + 1;

logger.info("range>>>>>>>>>>>"+range);

// compute a fraction of the range, 0 <= frac < range

long fraction = (long)(range * aRandom.nextDouble());

logger.info("fraction>>>>>>>>>>>>>>>>>>>>"+fraction);

int randomNumber = (int)(fraction + aStart);

logger.info("Generated : " + randomNumber);

}

回答:

我认为您获得8/9位数字值和负数的原因是您要添加fraction一个long(带符号的64位值),该值可能大于的正数int范围(32位值)aStart

该值正在溢出,randomNumber处于负32位范围内或几乎缠绕到aStart(由于int是带符号的32位值,您fraction只需要稍微小于(2

^ 32- aStart)就可以看到8或9位数字)。

您需要使用long所有值。

   private static void createRandomInteger(int aStart, long aEnd, Random aRandom){

if ( aStart > aEnd ) {

throw new IllegalArgumentException("Start cannot exceed End.");

}

//get the range, casting to long to avoid overflow problems

long range = aEnd - (long)aStart + 1;

logger.info("range>>>>>>>>>>>"+range);

// compute a fraction of the range, 0 <= frac < range

long fraction = (long)(range * aRandom.nextDouble());

logger.info("fraction>>>>>>>>>>>>>>>>>>>>"+fraction);

long randomNumber = fraction + (long)aStart;

logger.info("Generated : " + randomNumber);

}

以上是 在Java中生成10位唯一的随机数 的全部内容, 来源链接: utcz.com/qa/433067.html

回到顶部