0

I need to write a constructor which will generate a random 6 length char. i've used : code=UUID.randomUUID();

and i thought of using :

if (code.length() != 6 ) {
 code=UUID.randomUUID();
 }

but there is an error which says method lenght() is undefined for type UUID. What else can i do?

  • 1
    http://stackoverflow.com/questions/41107/how-to-generate-a-random-alpha-numeric-string – prasanth Apr 03 '17 at 19:45
  • You haven't actually initialized code before calling code.length. – Ishnark Apr 03 '17 at 19:46
  • 1
    Possible duplicate of [How to generate a random alpha-numeric string?](http://stackoverflow.com/questions/41107/how-to-generate-a-random-alpha-numeric-string) – рüффп Apr 03 '17 at 21:06

2 Answers2

1

Try using RandomStringUtils from org.apache.commons.lang3. You can use RandomStringUtils.randomAlphanumeric(6) then

Carlos
  • 71
  • 3
1

Go with Carlos's answer, as it's a better way to get a random String of length 6 than using a UUID, but I wanted to let you know why you're seeing that error.

UUID.randomUUID() returns a instance of the class UUID. It does not have a length method.

If you want to treat it as a String, you must first call .toString() on it, i.e. String code = UUID.randomUUID().toString();

Now that it is a String, you can use the length method.

Michael Peyper
  • 6,814
  • 2
  • 27
  • 44