java生成10个随机数,在java中生成10位唯一随机数

I am trying with below code to generate 10 digits unique random number. As per my req i have to create around 5000 unique numbers(ids). This is not working as expected. It also generates -ve numbers. Also sometimes one or two digits are missing in generated number resulting in 8 or 9 numbers not 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);

}

解决方案

I think the reason you're getting 8/9 digit values and negative numbers is that you're adding fraction, a long (signed 64-bit value) which may be larger than the positive int range (32-bit value) to aStart.

The value is overflowing such that randomNumber is in the negative 32-bit range or has almost wrapped around to aStart (since int is a signed 32-bit value, fraction would only need to be slightly less than (2^32 - aStart) for you to see 8 or 9 digit values).

You need to use long for all the values.

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);

}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值