简体   繁体   中英

11 Digit random number in Java

I have to generate an eleven digit ID number but when I use random package, it says that it is out of range, so how can I make it eleven?

public static int generateID(){

    Random r = new Random();
    int numbers = 1000000000 + (int)(r.nextDouble() * 999999999);

    return numbers;
}

To ensure uniform distribution, you should use the nextInt(int bound) method.

Since it cannot generate 11 digit numbers (exceeds capacity of int ), you need to call it twice, eg to get last 9 digits (000000000-999999999), and first 2 digits (10-99).

Remember to use long somewhere to prevent int overflow.

long numbers = r.nextInt(1_000_000_000)               // Last 9 digits
             + (r.nextInt(90) + 10) * 1_000_000_000L; // First 2 digits
import java.util.concurrent.ThreadLocalRandom;
...
public long generateId() {
  ThreadLocalRandom random = ThreadLocalRandom.current();
  return random.nextLong(10_000_000_000L, 100_000_000_000L);
}

Use the right tool. In this case, Random is worth much less than ThreadLocalRandom .

Here :

int numbers = 1000000000 + (int)(r.nextDouble() * 999999999);

r.nextDouble() * 999999999 produces a number with 8 digits.
Additioning 1000000000 that contains 10 digits to a number that contains 8 digits will never produce a number that contains 11 digits.

Besides, 11 digits requires a long not an int as Integer.MAX_VALUE == 2147483647 (10 digits).

To get a 11 digits number, you can do :

 long n = 10000000000L + ((long)rnd.nextInt(900000000)*100) + rnd.nextInt(100);

((long)rnd.nextInt(900000000)*100) + rnd.nextInt(100) returns a number between 0 and 89 999 999 999 .
Additionating this number to 10 000 000 000 will produce a number with 11 digits between 0 and 99 999 999 999 .

For example, try that :

public static long generateID() {
      return 10000000000L + ((long)rnd.nextInt(900000000)*100) + rnd.nextInt(100);
}

The maximum value of a Java 'int' is 2147483647. Ten digits, and only 9 unless you constrain it below that value.

There are several ways to handle this, but the easiest would be to use the datatype 'long' instead of 'int'. The max value of a 'long' is 19 digits, and should support your use case.

Use a long . Like this:

public static int generateID(){

    Random r = new Random();
    long numbers = 1000000000L + (long)(r.nextDouble() * 999999999L);

    return numbers;
}

The “L” are to explicitly tell the compiler that we want long s, not int s.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM