Is there functionality to generate a random character in Java?

前端 未结 18 2029
难免孤独
难免孤独 2020-11-28 06:00

Does Java have any functionality to generate random characters or strings? Or must one simply pick a random integer and convert that integer\'s ascii code to a character?

相关标签:
18条回答
  • 2020-11-28 06:16

    You could also use the RandomStringUtils from the Apache Commons project:

    Dependency:

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

    Usages:

    RandomStringUtils.randomAlphabetic(stringLength);
    RandomStringUtils.randomAlphanumeric(stringLength);
    
    0 讨论(0)
  • 2020-11-28 06:16

    polygenelubricants' answer is also a good solution if you only want to generate Hex values:

    /** 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 讨论(0)
  • 2020-11-28 06:16

    I use this:

    char uppercaseChar = (char) ((int)(Math.random()*100)%26+65);
    
    char lowercaseChar = (char) ((int)(Math.random()*1000)%26+97);
    
    0 讨论(0)
  • 2020-11-28 06:18

    using dollar:

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

    given chars you can build a "shuffled" range of characters:

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

    then taking the first n chars, you get a random string of length n. The final code is simply:

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

    NB: the condition n > 0 is cheched by slice

    EDIT

    as Steve correctly pointed out, randomString uses at most once each letter. As workaround you can repeat the alphabet m times before call shuffle:

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

    or just provide your alphabet as String:

    public String randomStringFromAlphabet(String alphabet, int n) {
        return $(alphabet).shuffle().slice(n).toString();
    }
    
    String s = randomStringFromAlphabet("00001111", 4);
    
    0 讨论(0)
  • 2020-11-28 06:20

    In following 97 ascii value of small "a".

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

    in above 3 number for a , b , c or d and if u want all character like a to z then you replace 3 number to 25.

    0 讨论(0)
  • 2020-11-28 06:21

    You could use generators from the Quickcheck specification-based test framework.

    To create a random string use anyString method.

    String x = anyString();
    

    You could create strings from a more restricted set of characters or with min/max size restrictions.

    Normally you would run tests with multiple values:

    @Test
    public void myTest() {
      for (List<Integer> any : someLists(integers())) {
        //A test executed with integer lists
      }
    }
    
    0 讨论(0)
提交回复
热议问题