Generating 10 digits unique random number in java
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
.
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);
}