Link to home
Start Free TrialLog in
Avatar of InGodsGrace
InGodsGrace

asked on

How to generate Unique ID using Java Programming?

Hi to anybody who can help,
I need to know how to generate a 6-digit unique ID using java programming. Take a scenario for example: An atm machine program prompt user for personal details. After validating the detail, it will issue an 6 digit unique customer ID and display it on the screen. (it has to be 6 digits)

Blessings,
Christine
Avatar of sunnycoder
sunnycoder
Flag of India image

Hi InGodsGrace,

highest 6 digit number is 999999 .... choose a prime number less than 999999 .... call it k

- seed random number generator with current time
- generate a random number n
- first number to use will ne n mod 999999
- next, (first+k) mod 999999
- next (second +k ) mod 999999

or for that matter you can use sequential ids too !!! or is it that you need random sequential ids ? If the pattern or difference of k between consecutive ids is weak, then you will have to keep track of ids already generated which can be expensive in terms of memory

Sunnycoder
an oops
> you need random sequential ids ?
random unique ids

Sunnycoder
Avatar of InGodsGrace
InGodsGrace

ASKER

Hi sunnycoder,
thks for the fast reply...

Yeah, it would be better if it could be randomise....

btw, any web link to recommend for information regarding seed and random ? i have totally no clue what it mean even though i have read info abt them..(am really weak in java)

Appreciate,
Christine
import java.util.Random;

class RandomIDGenerator {
    public RandomIDGenerator() {
        rand = new Random( System.currentTimeMillis() );
    }
    public int generate() {
        while ( true  ) {
            // You specified you wanted a PRIME number.... otherwise just "return rand.nextInt( 999999 );"
            int num = rand.nextInt( 999999 );
            if( isPrime( num ) ) {
                return num;
            }
        }
    }

    // Probably a better primality test available somewhere!!!
    private boolean isPrime( int number ) {
        if( number %2 == 0  ) return false;
        for( int i = 3; i <= Math.sqrt( number ); i+=2 ) {
            if( number % i == 0 ) return false;
        }
        return true;
}
hi,

sorry, forgot you need private attribute "rand"... code reposted below, including sample main() to generate 100 values...

import java.util.Random;

class RandomIDGenerator {
    private Random rand;
    public RandomIDGenerator() {
        rand = new Random( System.currentTimeMillis() );
    }
    public int generate() {
        while ( true  ) {
            // You specified you wanted a PRIME number.... otherwise just "return rand.nextInt( 999999 );"
            int num = rand.nextInt( 999999 );
            if( isPrime( num ) ) {
                return num;
            }
        }
    }

    // Probably a better primality test available somewhere!!!
    private boolean isPrime( int number ) {
        if( number %2 == 0  ) return false;
            for( int i = 3; i <= Math.sqrt( number ); i+=2 ) {
                if( number % i == 0 ) return false;
            }
        return true;
    }

    private static void main( String[] args ) {
        RandomIDGenerator gen = RandomIDGenerator();
        for( int i = 0; i != 100; i++ ) {
            System.out.println( gen.generate() );
        }  
    }  
}
ASKER CERTIFIED SOLUTION
Avatar of cjjclifford
cjjclifford

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Thank you thank you for all ur advice, sunnycoder and cjjclifford ...

cjjclifford , I was wondering why do u put currentTimeMillis when you create a random object....what has time got to do with randoming the number? hmmm.....perhap u shed some light?? :D

And how do make the randomise number to be displayed as 6 digit if it is not 6 digit eg. to make 100 displayed as 000100

Bless ya,
Christine
Hello,

I refer to the codes send by cjjclifford.

import java.util.Random;
class MeowTest{
    private Random rand;
    public MeowTest() {
        rand = new Random( System.currentTimeMillis() );
    }

    public String generate() {
      String[] digit = new String[6];
      String result = "";

      for (int i = 0; i < 6; i++)
      {
            digit[i] = Integer.toString(rand.nextInt( 9 ));
            result += digit[i];
      }

      
        return result;
    }  

    public static void main( String[] args ) {
        MeowTest gen = new MeowTest();
        for( int i = 0; i != 10; i++ ) {
            System.out.println( gen.generate() );
        }  
    }  
}

I hope that helps....
Dear christine,

The reason behind the use of System.currentTimeMillis is to generate the different number. If you do not use the currentTimeMillis, then the generated random number will always be the same. Since the currentTimeMillis will always changed, it means that the generated random number will also be various.

That is the reason.

I hope that helps

Hi Christine,

Sorry I didn't reply, somehow missed notification of the update to the topic. To use a Random number generator a "seed" value has to be given to the function that generates the sequence of numbers. Since the same function to generate the sequence will not change (since its standard library), if the same seed value is supplied the identical sequence of numbers will be generated.
I used System.currentTimeMillis() as the seed number since this will change every time the program is run.

With regards to how to have exactly 6 characters, the following code is probably a little simpler than that by suprapto45:

// Add this method to the class I posted before - this '0' left-pads a generated integer to a length of 6, while only calling
// Random.nextInt() once (i.e. to get the random code itself) - more efficient than repeatedly calling random.nextInt()...
public String generatePaddedCode() {
    String unpadded = Integer.toString( gen.generate() );
    StringBuffer padded = new StringBuffer();
    for( int i = 0; i != 6 - unpadded.length(); i++ ) {
        padded.append( '0' );
    }
    padded.append( unpadded );
    return padded;
}
Sorry, some code errors in that (not calling toString() on the StringBuffer for one!) Also, the padding and the generate() methods should probably be combined, so the generation class would actually become:

import java.util.Random;
class RandomIDGenerator {
    private Random rand;
    public RandomIDGenerator() {
        rand = new Random( System.currentTimeMillis() );
    }
    public String generate() {
        String unpadded = Integer.toString( rand.nextInt( 999999 ) );
        StringBuffer padded = new StringBuffer();
        for( int i = 0; i != 6 - unpadded.length(); i++ ) {
            padded.append( '0' );
        }
        padded.append( unpadded );
        return padded.toString();
    }  

    public static void main( String[] args ) {
        RandomIDGenerator gen = new RandomIDGenerator();
        for( int i = 0; i != 100; i++ ) {
            System.out.println( gen.generate() );
        }  
    }  
}