lundi 31 août 2020

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.




Aucun commentaire:

Enregistrer un commentaire