This question already has an answer here:
As the title suggest I need to create a random, 17 characters long, ID. Something like "AJB53JHS232ERO0H1
". The order of letters and numbers is also random. I thought of creating an array with letters A-Z and a 'check' variable that randoms to 1-2
. And in a loop;
Randomize 'check' to 1-2.
If (check == 1) then the character is a letter.
Pick a random index from the letters array.
else
Pick a random number.
But I feel like there is an easier way of doing this. Is there?
You can easily do that with a for loop,
Three steps to implement your function:
Step#1 You can specify a string, including the chars A-Z and 0-9.
Like.
Step#2 Then if you would like to generate a random char from this candidate string. You can use
Step#3 At last, specify the length of random string to be generated (in your description, it is 17). Writer a for-loop and append the random chars generated in step#2 to StringBuilder object.
Based on this, here is an example public class RandomTest {
Here you can use my method for generating Random String
The above method from my bag using to generate a salt string for login purpose.
RandomStringUtils
from Apache commons-lang might help:2017 update:
RandomStringUtils
has been deprecated, you should now use RandomStringGenerator.