-5

I need to generate random alphanumeric string (5 or 6 char) in order to put it to specific field. Could anyone pls provide me solution ? Have tried several methods described in another posts on stack but without success.

Have tried something like that:

public static String generateString(Random rng, String characters, int length)
{
    char[] text = new char[length];
    for (int i = 0; i < length; i++)
    {
        text[i] = characters.charAt(rng.nextInt(characters.length()));
    }
    return new String(text);
}

but no idea why random is passed as an argument and what should I provide for it while calling method

drkthng
  • 6,651
  • 7
  • 33
  • 53
Michau
  • 59
  • 1
  • 9
  • 3
    _Have tried several methods_ Can you pease post your attempts, and tell us what didn't work, why, what you expected and what is happening instead? – BackSlash Sep 15 '15 at 07:50

2 Answers2

2

Since you attempted many as you stated, I can help you with one of the easiest solutions-

  1. Have a string declared with characters of your choice. e.g. 0..9..a..z..A..Z
  2. Have a loop with the number of characters you would like to generate. e.g. if you want 5 random characters, you would have something like for(int i = 0; i < 5; i++)
  3. For each iteration, pick a random character from step 1 using the length of the string you have in step 1.
Sajal Dutta
  • 18,272
  • 11
  • 52
  • 74
  • yes just write every character manually. Only with alphanumeric ones your have 62 characters to write and you can forget one... – Erwan C. Sep 15 '15 at 08:08
1

Here is a sample code:

private static final char[] VALID_CHARACTERS =
        "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456879".toCharArray();

public static String getRandomString( final int length ) {
    // Check input
    if( length <= 0 ) {
        return "";
    }
    // Generate string
    Random rand = new Random();
    char[] buffer = new char[length];
    for( int i = 0; i < length; ++i ) {
        buffer[i] = VALID_CHARACTERS[rand.nextInt( VALID_CHARACTERS.length )];
    }
    //
    return new String( buffer );
}

This simple method uses a constant of valid characters, polling randomly a character per time from it to build the string of the desired length.

For example, to get an alphanumeric string of 10 characters, you call the method this way:

getRandomString( 10 );
robyfonzy
  • 19
  • 2