Existe-t-il une fonctionnalité pour générer un caractère aléatoire en Java?


Java a-t-il des fonctionnalités pour générer des caractères ou des chaînes aléatoires? Ou faut - il simplement choisir un entier aléatoire et convertir le code ascii de cet entier en un caractère?

Author: Chris, 2010-04-13

19 answers

Il y a plusieurs façons de le faire, mais oui, cela implique de générer un int aléatoire (en utilisant par exemple java.util.Random.nextInt) et puis en utilisant cela pour mapper à un char. Si vous avez un alphabet spécifique, alors quelque chose comme ça est astucieux:

    import java.util.Random;

    //...

    Random r = new Random();

    String alphabet = "123xyz";
    for (int i = 0; i < 50; i++) {
        System.out.println(alphabet.charAt(r.nextInt(alphabet.length())));
    } // prints 50 random characters from alphabet

Remarque que java.util.Random est en fait un pseudo-générateur de nombre aléatoire, basé sur la plutôt faible congruence linéaire de formule. Vous avez mentionné la nécessité de la cryptographie; vous voudrez peut-être étudier l'utilisation d'un générateur de pseudorandomes cryptographiquement sécurisé dans ce cas (par exemple java.security.SecureRandom).

 95
Author: polygenelubricants, 2010-04-13 04:43:56

Pour générer un caractère aléatoire dans a-z:

Random r = new Random();
char c = (char)(r.nextInt(26) + 'a');
 139
Author: dogbane, 2010-04-13 07:45:30

Vous pouvez également utiliser les RandomStringUtils du projet Apache Commons:

Dépendance:

<dependency> 
  <groupId>org.apache.commons</groupId> 
  <artifactId>commons-lang3</artifactId> 
  <version>3.8.1</version> 
</dependency>

Utilisations:

RandomStringUtils.randomAlphabetic(stringLength);
RandomStringUtils.randomAlphanumeric(stringLength);
 75
Author: Josema, 2020-01-06 12:25:14
private static char rndChar () {
    int rnd = (int) (Math.random() * 52); // or use Random or whatever
    char base = (rnd < 26) ? 'A' : 'a';
    return (char) (base + rnd % 26);

}

Génère des valeurs dans les plages a-z, A-Z.

 14
Author: Peter Walser, 2010-04-13 08:04:53
String abc = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";

char letter = abc.charAt(rd.nextInt(abc.length()));

Celui-ci fonctionne aussi bien.

 9
Author: Ricardo Vallejo, 2018-05-04 19:47:45

En suivant 97 valeur ascii de petit "a".

public static char randomSeriesForThreeCharacter() {
Random r = new Random();
char random_3_Char = (char) (97 + r.nextInt(3));
return random_3_Char;
}

Dans le numéro 3 ci-dessus pour a , b , c ou d et si vous voulez tous les caractères comme a à z, vous remplacez le numéro 3 par 25.

 4
Author: duggu, 2012-12-24 12:25:32

Vous pouvez utiliser des générateurs du Cadre de test basé sur les spécifications Quickcheck.

Pour créer une chaîne aléatoire, utilisez la méthode anyString.

String x = anyString();

Vous pouvez créer des chaînes à partir d'un ensemble de caractères plus restreint ou avec des restrictions de taille min/max.

Normalement, vous exécutez des tests avec plusieurs valeurs:

@Test
public void myTest() {
  for (List<Integer> any : someLists(integers())) {
    //A test executed with integer lists
  }
}
 1
Author: Thomas Jung, 2010-04-13 07:19:11

En utilisant dollar :

Iterable<Character> chars = $('a', 'z'); // 'a', 'b', c, d .. z

Étant donné chars vous pouvez créer une plage de caractères" mélangée":

Iterable<Character> shuffledChars = $('a', 'z').shuffle();

, Puis prendre la première n caractères, vous obtenez une chaîne aléatoire de longueur n. Le code final est simplement:

public String randomString(int n) {
    return $('a', 'z').shuffle().slice(n).toString();
}

NB: - la condition n > 0 est cheched par slice

MODIFIER

Comme Steve l'a correctement souligné, randomString utilise au plus une fois chaque lettre. Comme solution de contournement vous pouvez répéter l'alphabet m fois avant d'appeler shuffle:

public String randomStringWithRepetitions(int n) {
    return $('a', 'z').repeat(10).shuffle().slice(n).toString();
}

Ou tout simplement fournir votre alphabet comme String:

public String randomStringFromAlphabet(String alphabet, int n) {
    return $(alphabet).shuffle().slice(n).toString();
}

String s = randomStringFromAlphabet("00001111", 4);
 1
Author: dfa, 2010-04-13 09:29:11

C'est une découverte simple mais utile. Il définit une classe nommée RandomCharacter avec 5 méthodes surchargées pour obtenir un certain type de caractère au hasard. Vous pouvez utiliser ces méthodes dans vos futurs projets.

    public class RandomCharacter {
    /** Generate a random character between ch1 and ch2 */
    public static char getRandomCharacter(char ch1, char ch2) {
        return (char) (ch1 + Math.random() * (ch2 - ch1 + 1));
    }

    /** Generate a random lowercase letter */
    public static char getRandomLowerCaseLetter() {
        return getRandomCharacter('a', 'z');
    }

    /** Generate a random uppercase letter */
    public static char getRandomUpperCaseLetter() {
        return getRandomCharacter('A', 'Z');
    }

    /** Generate a random digit character */
    public static char getRandomDigitCharacter() {
        return getRandomCharacter('0', '9');
    }

    /** Generate a random character */
    public static char getRandomCharacter() {
        return getRandomCharacter('\u0000', '\uFFFF');
    }
}

Pour démontrer comment cela fonctionne, jetons un coup d'œil au programme de test suivant affichant 175 lettres minuscules aléatoires.

public class TestRandomCharacter {
    /** Main method */
    public static void main(String[] args) {
        final int NUMBER_OF_CHARS = 175;
        final int CHARS_PER_LINE = 25;
        // Print random characters between 'a' and 'z', 25 chars per line
        for (int i = 0; i < NUMBER_OF_CHARS; i++) {
            char ch = RandomCharacter.getRandomLowerCaseLetter();
            if ((i + 1) % CHARS_PER_LINE == 0)
                System.out.println(ch);
            else
                System.out.print(ch);
        }
    }
}

Et la sortie est:

entrez la description de l'image ici

Si vous exécutez une fois de plus encore une fois:

entrez la description de l'image ici

Je donne du crédit à Y. Daniel Liangpour son livre Introduction to Java Programming, Comprehensive Version, 10th Edition, où j'ai cité ces connaissances et les utiliser dans mes projets.

Note : Si vous n'êtes pas familier avec les méthodes surchargées, en un mot, la surcharge de méthode est une fonctionnalité qui permet à une classe d'avoir plus d'une méthode ayant le même nom, si leurs listes d'arguments sont différentes.

 1
Author: Gulbala Salamov, 2019-04-14 07:02:12

Jetez un oeil à JavaRandomizer classe. Je pense que vous pouvez randomiser un caractère en utilisant la méthode randomize(char[] array).

 0
Author: manuel, 2010-04-13 04:00:10

Ma proposition pour générer une chaîne aléatoire avec une casse mixte comme: "DthJwMvsTyu".
Cet algorithme basé sur des codes ASCII de lettres lorsque ses codes a-z (97 à 122) et A-Z (65 à 90) diffèrent en 5ème bit (2^5 ou 1

random.nextInt(2): le résultat est 0 ou 1.

random.nextInt(2) << 5: le résultat est 0 ou 32.

Supérieure A est de 65 ans et inférieure a est de 97. La différence est seulement sur le 5ème bit (32) donc pour générer un caractère aléatoire, nous faisons binaire OU ' / ' aléatoire charCaseBit (0 ou 32) et code aléatoire de A à Z (65 à 90).

public String fastestRandomStringWithMixedCase(int length) {
    Random random = new Random();
    final int alphabetLength = 'Z' - 'A' + 1;
    StringBuilder result = new StringBuilder(length);
    while (result.length() < length) {
        final char charCaseBit = (char) (random.nextInt(2) << 5);
        result.append((char) (charCaseBit | ('A' + random.nextInt(alphabetLength))));
    }
    return result.toString();
}
 0
Author: Marcin Programista, 2018-03-05 11:03:30

Voici le code pour générer du code alphanumérique aléatoire. Vous devez d'abord déclarer une chaîne de caractères que vous souhaitez inclure dans un nombre aléatoire.et définissez également la longueur maximale de la chaîne

 SecureRandom secureRandom = new SecureRandom();
 String CHARACTERS = "ABCDEFGHIJKLMNOPQRSTUVWXYZ123456789";
    StringBuilder generatedString= new StringBuilder();
    for (int i = 0; i < MAXIMUM_LENGTH; i++) {
        int randonSequence = secureRandom .nextInt(CHARACTERS.length());
        generatedString.append(CHARACTERS.charAt(randonSequence));
    }

Utilisez la méthode toString () pour obtenir une chaîne à partir de StringBuilder

 0
Author: Abhishek Jha, 2018-12-07 12:53:43

La réponse de Polygenelubricants est également une bonne solution si vous souhaitez uniquement générer des valeurs hexadécimales:

/** A list of all valid hexadecimal characters. */
private static char[] HEX_VALUES = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '0', 'A', 'B', 'C', 'D', 'E', 'F' };

/** Random number generator to be used to create random chars. */
private static Random RANDOM = new SecureRandom();

/**
 * Creates a number of random hexadecimal characters.
 * 
 * @param nValues the amount of characters to generate
 * 
 * @return an array containing <code>nValues</code> hex chars
 */
public static char[] createRandomHexValues(int nValues) {
    char[] ret = new char[nValues];
    for (int i = 0; i < nValues; i++) {
        ret[i] = HEX_VALUES[RANDOM.nextInt(HEX_VALUES.length)];
    }
    return ret;
}
 0
Author: schnatterer, 2019-04-10 11:34:03

En fait, les méthodes mentionnées ne génèrent pas de caractère aléatoire réel. Pour générer de vrais caractères aléatoires, vous devez lui donner une graine aléatoire! dans l'exemple de temps en milliseconde. ce code génère 10 caractères aléatoires, puis le convertit en chaîne:

import java.util.Random;
public class MyClass {
    public static void main() {

     String randomKey;

    char[] tempArray={0,0,0,0,0,0,0,0,0,0};  //ten characters

    long seed=System.currentTimeMillis();
    Random random=new Random(seed);
    for (int aux=0; aux<10;aux++){

        tempArray[aux]=(char) random.nextInt(255);
        System.out.println(tempArray[aux]);
    }

    randomKey=String.copyValueOf(tempArray);  


      System.out.println(randomKey);
    }
}
 0
Author: Farshid Ahmadi, 2020-01-26 18:18:52

J'utilise ceci:

char uppercaseChar = (char) ((int)(Math.random()*100)%26+65);

char lowercaseChar = (char) ((int)(Math.random()*1000)%26+97);
 0
Author: Andrewsz82, 2020-04-25 14:30:47

java.util.Random est le plus efficace que j'ai essayé jusqu'à présent, ayant une précision de 98.65% l'unicité. J'ai fourni ci-dessous quelques tests qui génèrent 10000 lots d'une centaine de chaînes de caractères alphanumériques 2 et calcule la moyenne.

D'autres outils aléatoires étaient RandomStringUtils de commons.lang3 et java.util.Math.

public static void main(String[] args) {
    int unitPrintMarksTotal = 0;
    for (int i = 0; i < 10000; i++) {
        unitPrintMarksTotal += generateBatchOfUniquePrintMarks(i);
    }

    System.out.println("The precision across 10000 runs with 100 item batches is: " + (float) unitPrintMarksTotal / 10000);
}

private static int generateBatchOfUniquePrintMarks(int batch) {
    Set<String> printMarks = new HashSet<>();
    for (int i = 0; i < 100; i++) {
        printMarks.add(generatePrintMarkWithJavaUtil());
    }

    System.out.println("Batch " + batch + " Unique number of elements is " + printMarks.size());

    return printMarks.size();
}

// the best so far => 98.65
// with 3 chars => 99.98
// with 4 chars => 99.9997
private static String generatePrintMarkWithJavaUtil() {
    int leftLimit = 48; // numeral '0'
    int rightLimit = 122; // letter 'z'
    int targetStringLength = 2;
    String printMark;
    do {
        printMark = new Random().ints(leftLimit, rightLimit + 1)
                .filter(i -> (i <= 57 || i >= 65) && (i <= 90 || i >= 97))
                .limit(targetStringLength)
                .collect(StringBuilder::new, StringBuilder::appendCodePoint, StringBuilder::append)
                .toString();
    } while (!isValid(printMark));

    return printMark;
}

// 95.46
private static String generatePrintMarkWithCommonsLang3() {
    String printMark;
    do {
        printMark = RandomStringUtils.randomAlphanumeric(2).toUpperCase();
    } while (!isValid(printMark));

    return printMark;
}

// 95.92
private static String generatePrintMarkWithMathRandom() {
    final String ALPHA_NUMERIC_STRING = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
    StringBuilder printMark;
    do {
        printMark = new StringBuilder();
        int i = (int) (Math.random() * ALPHA_NUMERIC_STRING.length());
        printMark.append(ALPHA_NUMERIC_STRING.charAt(i));
        int j = (int) (Math.random() * ALPHA_NUMERIC_STRING.length());
        printMark.append(ALPHA_NUMERIC_STRING.charAt(j));
    } while (!isValid(printMark.toString()));

    return printMark.toString();
}

private static boolean isValid(final String printMark) {
    return true;
}
 0
Author: aurelius, 2021-01-07 12:05:49

Si cela ne vous dérange pas d'ajouter une nouvelle bibliothèque dans votre code, vous pouvez générer des caractères avec MockNeat (avertissement: Je suis l'un des auteurs).

MockNeat mock = MockNeat.threadLocal();

Character chr = mock.chars().val();
Character lowerLetter = mock.chars().lowerLetters().val();
Character upperLetter = mock.chars().upperLetters().val();
Character digit = mock.chars().digits().val();
Character hex = mock.chars().hex().val(); 
 -1
Author: Andrei Ciobanu, 2017-03-05 19:38:12
public static void  main(String[] args) {

  //  System.out.println("Enter a number to changeit at char  ");
    Random random = new Random();

    int x = random.nextInt(26)+65;    //0  to 25
    System.out.println((char)x);
}
 -1
Author: ArsamP, 2020-03-26 10:09:09
   Random randomGenerator = new Random();

   int i = randomGenerator.nextInt(256);
   System.out.println((char)i);

Devez prendre soin de ce que vous voulez, en supposant que vous envisagez '0,'1','2'.. en tant que caractères.

 -2
Author: ring bearer, 2010-04-13 04:52:10