Improve company productivity with a Business Account.Sign Up

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 1604
  • Last Modified:

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
0
InGodsGrace
Asked:
InGodsGrace
  • 5
  • 3
  • 2
  • +1
1 Solution
 
sunnycoderCommented:
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
 
sunnycoderCommented:
an oops
> you need random sequential ids ?
random unique ids

Sunnycoder
0
 
InGodsGraceAuthor Commented:
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
What Kind of Coding Program is Right for You?

There are many ways to learn to code these days. From coding bootcamps like Flatiron School to online courses to totally free beginner resources. The best way to learn to code depends on many factors, but the most important one is you. See what course is best for you.

 
sunnycoderCommented:
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
 
cjjcliffordCommented:
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
 
cjjcliffordCommented:
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
 
cjjcliffordCommented:
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
 
InGodsGraceAuthor Commented:
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
 
suprapto45Commented:
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
 
suprapto45Commented:
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
 
cjjcliffordCommented:
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
 
cjjcliffordCommented:
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
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Featured Post

Upgrade your Question Security!

Your question, your audience. Choose who sees your identity—and your question—with question security.

  • 5
  • 3
  • 2
  • +1
Tackle projects and never again get stuck behind a technical roadblock.
Join Now