-2

I need some guidance on auto generating unique numbers. I have never done this before so I don't have much of an idea where to start and was wondering if someone could help me out.

I need to auto generate a number that is a single letter followed by a four digit number. e.g: b1678 but guarantee that no number is the same (need to do for 30 different things)

Thanks a lot for your help!!

Jack
  • 35
  • 5
  • 3
    First: what does "unique" really mean? "Unique" while one instance of the program runs; or "unique" for all runs for all times on all machines that run it? Second: SO doesn't work this way. Instead of dropping your requirements, you show us what you have **done** so far. And you ask specific questions about where exactly you are blocked. But don't expect other people to serve ready-to-use code to you. – GhostCat May 02 '16 at 12:57
  • https://commons.apache.org/proper/commons-lang/javadocs/api-2.6/org/apache/commons/lang/RandomStringUtils.html – soorapadman May 02 '16 at 13:02
  • http://stackoverflow.com/questions/2178992/how-to-generate-unique-id-in-java-integer – Nezir May 02 '16 at 13:15
  • http://stackoverflow.com/questions/8115722/generating-unique-random-numbers-in-java – Nezir May 02 '16 at 13:15
  • 1
    @Jack I am only explaining to you that your question lacks certain important pieces of information. And the fact that you don't like to be told ... doesn't invalidate my claim that you are expected to you show **your work** first when you expect others to help you. You can turn to the stack overflow help center in case you think this is about "being a dick" towards you. And for the "unique" thing: if you read the answers you got, you will find that they actually lead to a different understanding of "unique". – GhostCat May 02 '16 at 14:08

2 Answers2

1

If you want unique identifiers, use UUID u = UUID.randomUUID();

If you want only numbers, use

    public void Integer getRandom() {
        ArrayList<Integer> list = new ArrayList<Integer>();
        for (int i=1; i<n; i++) {
            list.add(new Integer(i));
        }
        Collections.shuffle(list);
        return list.get(0);
    }
Yogesh Patil
  • 908
  • 4
  • 14
0

For the format that you have given, you can do:

Random r = new Random();
String str = ""+((char)(r.nextInt(26)+97)); // for the first character
while(str.length()<5) //to add only till the length is less than 5.
{
    int n = r.nextInt(10); // get  new number
    if(!str.contains(n+"")) str+=n; // add only if it does not already contain the number.
}
dryairship
  • 6,022
  • 4
  • 28
  • 54