Solved

How to generate Unique ID using Java Programming?

Posted on 2004-09-02
13
1,046 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 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
Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
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

Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

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

Suggested Solutions

Title # Comments Views Activity
scoresSpecial  challenge 13 69
count7 challenge 12 138
drawing animated level bar based on numbers 3 122
Excel file not created as expected 7 111
If you haven’t already, I encourage you to read the first article (http://www.experts-exchange.com/articles/18680/An-Introduction-to-R-Programming-and-R-Studio.html) in my series to gain a basic foundation of R and R Studio.  You will also find the …
The purpose of this article is to demonstrate how we can use conditional statements using Python.
This video teaches viewers about errors in exception handling.
The viewer will learn how to user default arguments when defining functions. This method of defining functions will be contrasted with the non-default-argument of defining functions.

751 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