Joshua Java

Random Number Generator

Posted on: April 1, 2008

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:

5 Responses to "Random Number Generator"

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

Bisa tolong dijelaskan ini code utk fungsi apaan dan termasuk package apaan?
Thanks

Hlo salam kenal, ikutan nimbrung ya ..

@anto
kode itu buat logging, kalo gak salah itu pake Slf4j API (Simple Logging Facade 4 Java): http://www.slf4j.org/

Halo, bukankah kalo cara generatenya seperti itu, kita ngga bisa dapetin PIN yang digit depannya 0 ?

Lagipula, cara seperti ini lebih simple😀.

import java.util.*;
public class RandomGenerator
{
private static Random random = new Random();
public static String generate(int length)
{
String ret = new String(“”);
for(int i=0;i<length;i++)
ret += (char)(random.nextInt(10)+’0′);
return ret;
}
}

Hi Timotius,
Thanks buat masukannya. Gak pernah kepikiran sampe situ. Hehehe.

Good one..

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: