Solved

How to generate Unique ID using Java Programming?

Posted on 2004-09-02
13
1,004 Views
Last Modified: 2011-09-20
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
0
Comment
Question by:InGodsGrace
  • 5
  • 3
  • 2
  • +1
13 Comments
 
LVL 45

Expert Comment

by:sunnycoder
ID: 11961589
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
0
 
LVL 45

Expert Comment

by:sunnycoder
ID: 11961596
an oops
> you need random sequential ids ?
random unique ids

Sunnycoder
0
 

Author Comment

by:InGodsGrace
ID: 11961634
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
0
Free Tool: IP Lookup

Get more info about an IP address or domain name, such as organization, abuse contacts and geolocation.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

 
LVL 45

Expert Comment

by:sunnycoder
ID: 11961754
Hi Christine,

I am not a Java programmer so all I can give you is links or C code

here you go
http://www.math.utah.edu/~alfeld/Random/Random.html
http://java.sun.com/j2se/1.3/docs/api/java/util/Random.html
http://www.honeylocust.com/RngPack/
0
 
LVL 11

Expert Comment

by:cjjclifford
ID: 11962030
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;
}
0
 
LVL 11

Expert Comment

by:cjjclifford
ID: 11962057
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() );
        }  
    }  
}
0
 
LVL 11

Accepted Solution

by:
cjjclifford earned 125 total points
ID: 11962073
sorry, I've no idea where I got the idea you stated prime.... seeing things again!!!!
Code without prime is as follows:

import java.util.Random;
class RandomIDGenerator {
    private Random rand;
    public RandomIDGenerator() {
        rand = new Random( System.currentTimeMillis() );
    }
    public int generate() {
        return rand.nextInt( 999999 );
    }  

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

Author Comment

by:InGodsGrace
ID: 11969652
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
0
 
LVL 16

Expert Comment

by:suprapto45
ID: 11997281
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....
0
 
LVL 16

Expert Comment

by:suprapto45
ID: 11997310
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

0
 
LVL 11

Expert Comment

by:cjjclifford
ID: 11997660
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;
}
0
 
LVL 11

Expert Comment

by:cjjclifford
ID: 12004279
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() );
        }  
    }  
}
0

Featured Post

Active Directory Webinar

We all know we need to protect and secure our privileges, but where to start? Join Experts Exchange and ManageEngine on Tuesday, April 11, 2017 10:00 AM PDT to learn how to track and secure privileged users in Active Directory.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
post4 challenge 28 105
NotAlone Challenge 20 85
factory design pattern vs abstract factoy design pattern 2 115
Link failure 16 37
When we want to run, execute or repeat a statement multiple times, a loop is necessary. This article covers the two types of loops in Python: the while loop and the for loop.
Whether you’re a college noob or a soon-to-be pro, these tips are sure to help you in your journey to becoming a programming ninja and stand out from the crowd.
The viewer will be introduced to the technique of using vectors in C++. The video will cover how to define a vector, store values in the vector and retrieve data from the values stored in the vector.
The viewer will be introduced to the member functions push_back and pop_back of the vector class. The video will teach the difference between the two as well as how to use each one along with its functionality.

821 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question