Som
Som

Reputation: 1610

Alpha Numeric Random Number Sequence [5-digit or 6-digit or any digit] generation

Hi I am trying to generate a 5 digit random number which is alpha numeric in nature. I am doing both with without using Streams.

CODE

public class AlphaRandom {
    
    private static final String ALPHA_NUMERIC_STRING = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
    static final Random random = new Random();
    
    
    public static void main(String args[]) {
        int length = 5;
        String seq = randomAlphaNumeric(length);        
        System.out.println("Random Number Normal  : " +seq);        
        IntStream.range(0,1).forEach(i->System.out.println("Random Number Streams : " +generateRandomString(random, length)));
        
    }
    
    // Using Streams
    private static String generateRandomString(Random random, int length){
        return random.ints(48,122)
                .filter(i-> (i<57 || i>65) && (i <90 || i>97))
                .mapToObj(i -> (char) i)
                .limit(length)
                .collect(StringBuilder::new, StringBuilder::append, StringBuilder::append)
                .toString();
    }
    
    // Normal 
    public static String randomAlphaNumeric(int count) {

        StringBuilder builder = new StringBuilder();    
        while (count-- != 0) {  
            int character = (int)(Math.random()*ALPHA_NUMERIC_STRING.length()); 
            builder.append(ALPHA_NUMERIC_STRING.charAt(character)); 
        }   
        return builder.toString();
    }
}

Sample Outputs :

Random Number Normal  : VYAXC
Random Number Streams : LdBN6

Random Number Normal  : 2ANTT
Random Number Streams : hfegc

Random Number Normal  : JWK4Y
Random Number Streams : 8mQXK

But I am unable to generate the sequence always starting with a UpperCase only. Can someone help me out.

Upvotes: 0

Views: 253

Answers (2)

Virgula
Virgula

Reputation: 328

The easiest way is that before to return your string (once you have generated it), you take the first letter in order to apply toUpperCase and on the remaining chars, apply toLowerCase. Also, if in the future you will need to generate longer strings, you can use the same method without changing anything.

Summering what we'll do is:

public static String manipulate (String rand){
    String c = rand.substring(0,1); // where rand is the random alphanumeric generated by your methods, we pick the first char
    c = c.toUpperCase(); //we make it upperCase
    String split = rand.substring(1); //we get the remaining of the string starting from position 1
    split = split.toLowerCase(); //let's apply lowercase on the remaining
    String result = c+split; //join again
    return result;
}

Full Code:

package test;

import java.util.Random;
import java.util.stream.IntStream;

public class AlphaRandom {

    private static final String ALPHA_NUMERIC_STRING = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
    static final Random random = new Random();


    public static void main(String args[]) {
        int length = 5;
        String seq = randomAlphaNumeric(length);
        System.out.println("Random Number Normal  : " +seq);
        IntStream.range(0,1).forEach(i->System.out.println("Random Number Streams : " +generateRandomString(random, length)));

    }

    public static String manipulate (String rand){
        String c = rand.substring(0,1); // where rand is the random alphanumeric generated by your methods, we pick the first char
        c = c.toUpperCase(); //we make it upperCase
        String split = rand.substring(1); //we get the remaining of the string starting from position 1
        split = split.toLowerCase(); //let's apply lowercase on the remaining
        String result = c+split; //join the again
        return result;
    }

    // Using Streams
    private static String generateRandomString(Random random, int length){
        String rand =  random.ints(48,122)
                .filter(i-> (i<57 || i>65) && (i <90 || i>97))
                .mapToObj(i -> (char) i)
                .limit(length)
                .collect(StringBuilder::new, StringBuilder::append, StringBuilder::append)
                .toString();
        return manipulate(rand);
    }

    // Normal
    public static String randomAlphaNumeric(int count) {

        StringBuilder builder = new StringBuilder();
        while (count-- != 0) {
            int character = (int)(Math.random()*ALPHA_NUMERIC_STRING.length());
            builder.append(ALPHA_NUMERIC_STRING.charAt(character));
        }
        return manipulate(builder.toString());
    }
}

Output:

Random Number Normal  : Mwwsz
Random Number Streams : Q1fqk

Upvotes: 1

Ajay Kr Choudhary
Ajay Kr Choudhary

Reputation: 1362

I will use RandomStringUtils from the apache library to do this. The reason to do this is less code and I believe better readability of the code.

This is my code which can do the required thing

import org.apache.commons.lang3.RandomStringUtils;

public class GenerateRandomString {
    public static void main(String[] args) {
        int keyLength = 5; // Number of character allowed as per requirement
        String randomAlphanumeric = RandomStringUtils.randomAlphanumeric(keyLength);
        System.out.println("randomAlphanumeric generated is " + randomAlphanumeric);
        String upperCaseRandom = randomAlphanumeric.substring(0, 1).toUpperCase() + randomAlphanumeric.substring(1);
        System.out.println("upperCaseRandom generated is " + upperCaseRandom);
    }
}

It would generate the following output:

randomAlphanumeric generated is m8OiR
upperCaseRandom generated is M8OiR

I am making the first character to uppercase as required by question using the substring method.

Upvotes: 1

Related Questions