samedi 9 avril 2022

How can I create random strings with uppercase and lowercase in Java?

So, I found this function on the Internet and I would like to get some guidance on making strings use uppercase letters alongside lowercase ones, the code:

import java.util.Random;

public class randomstring {
    public void rand()
    {
        int leftLimit = 97; // letter 'a'
        int rightLimit = 122; // letter 'z'
        int targetStringLength = 5;
        Random random = new Random();
        StringBuilder buffer = new StringBuilder(targetStringLength);
        for (int i = 0; i < targetStringLength; i++) {
            int randomLimitedInt = leftLimit + (int) 
              (random.nextFloat() * (rightLimit - leftLimit + 1));
            buffer.append((char) randomLimitedInt);
        }
        String generatedString = buffer.toString();

        System.out.println(generatedString);
        
        
    }
    public static void main(String[] args) {
        randomstring random = new randomstring();
        random.rand();
    }
}



Aucun commentaire:

Enregistrer un commentaire