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);
}
Random random = new Random(); int rand15Digt = random. nextInt(15);
So you want a fixed length random number of 10 digits? This can be done easier:
long number = (long) Math.floor(Math.random() * 9_000_000_000L) + 1_000_000_000L;
Note that 10-digit numbers over Integer.MAX_VALUE
doesn't fit in an int
, hence the long
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With