How do I generate a random n digit integer in Java using the BigInteger class?

makaveli2178 picture makaveli2178 · Sep 14, 2010 · Viewed 19.6k times · Source

I am unsure about how to generate a random n digit integer in Java using the BigInteger class.

Answer

Eyal Schneider picture Eyal Schneider · Sep 14, 2010
private static Random rnd = new Random();

public static String getRandomNumber(int digCount) {
    StringBuilder sb = new StringBuilder(digCount);
    for(int i=0; i < digCount; i++)
        sb.append((char)('0' + rnd.nextInt(10)));
    return sb.toString();
}

And then you can use it:

new BigInteger(getRandomNumber(10000))