Joshua Java

Posts Tagged ‘Java

Recently I’ve got a task to generate a random PIN number. Now the PIN must be in 6 digit number. Here’s the number generator:

public class RandomGenerator {
    private static final Logger logger = LoggerFactory.getLogger(RandomGenerator.class);

    final static int [] sizeTable = { 0, 9, 99, 999, 9999, 99999, 999999, 9999999,
                                      99999999, 999999999, Integer.MAX_VALUE };

    private static Random random = new Random();

    public static int generate(int digit){
        int highest = sizeTable[digit] + 1;
        int lowest = sizeTable[digit -1] + 1;

        int generated = random.nextInt(highest);

        logger.debug(“Entry {}”, generated);

        if( generated < lowest )             generated = generate(digit);         return generated;     } } [/sourcecode] And to use it is as follows: [sourcecode language='java'] public class TestRandom {     private static final Logger logger = LoggerFactory.getLogger(TestRandom.class);     @Test public void random(){         logger.debug("Random {}", RandomGenerator.generate(6));     } } [/sourcecode] The parameter is the number of digit of number I want to generate and the maximum digit number is 9.

Tags: