Create Random Code

Discussion in 'Plugin Development' started by NiklasD_, Jun 20, 2013.

Thread Status:
Not open for further replies.
  1. Offline

    NiklasD_

    Hello,
    How can I create a Random Code with Numbers and characters?
    I want to save the Code in a String variable.

    Niklas
     
  2. Offline

    caldabeast

    Something like this should work if we're thinking along the same page:

    Code:java
    1.  
    2. char[] possible = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9'];
    3. Random r = new Random();
    4. StringBuilder sb = new StringBuilder();
    5. for(int i = 0; i < length; i++){ //length being the code's length
    6. sb.append(possible[r.nextInt(possible.length)]);
    7. }String code = sb.toString();
    8.  
     
  3. Offline

    NiklasD_

    Thank you this was that what I was looking for.
     
    caldabeast likes this.
  4. Offline

    Shiny Quagsire

    If your in need of a unique code guaranteed, you could also create a Hash of the current time. That way you don't accidentally create two identical codes. While it is unlikely that this one will produce two identical codes, it doesn't hurt to be safe. :)
     
  5. Offline

    Deckerz

    Another thing if the Random r = new Random(); goes into a method and not outside. it will generate the same number every time. (Well that what happened to me while making a plugin)

    Code:
    private Random r = new Random(); //rnd needs to be here for example
    public static void gen(){
    //code
    }
    
     
Thread Status:
Not open for further replies.

Share This Page