Is there functionality to generate a random character in Java?

前端 未结 18 2028
难免孤独
难免孤独 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:04
    String abc = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
    
    char letter = abc.charAt(rd.nextInt(abc.length()));
    

    This one works as well.

    0 讨论(0)
  • 2020-11-28 06:05
    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);
    
    }
    

    Generates values in the ranges a-z, A-Z.

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

    This is a simple but useful discovery. It defines a class named RandomCharacter with 5 overloaded methods to get a certain type of character randomly. You can use these methods in your future projects.

        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');
        }
    }
    

    To demonstrate how it works let's have a look at the following test program displaying 175 random lowercase letters.

    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);
            }
        }
    }
    

    and the output is:

    if you run one more time again:

    I am giving credit to Y.Daniel Liang for his book Introduction to Java Programming, Comprehensive Version, 10th Edition, where I cited this knowledge from and use in my projects.

    Note: If you are unfamiliar with overloaded methhods, in a nutshell Method Overloading is a feature that allows a class to have more than one method having the same name, if their argument lists are different.

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

    My propose for generating random string with mixed case like: "DthJwMvsTyu".
    This algorithm based on ASCII codes of letters when its codes a-z (97 to 122) and A-Z (65 to 90) differs in 5th bit (2^5 or 1 << 5 or 32).

    random.nextInt(2): result is 0 or 1.

    random.nextInt(2) << 5: result is 0 or 32.

    Upper A is 65 and lower a is 97. Difference is only on 5th bit (32) so for generating random char we do binary OR '|' random charCaseBit (0 or 32) and random code from A to Z (65 to 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 讨论(0)
  • 2020-11-28 06:14
       Random randomGenerator = new Random();
    
       int i = randomGenerator.nextInt(256);
       System.out.println((char)i);
    

    Should take care of what you want, assuming you consider '0,'1','2'.. as characters.

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

    To generate a random char in a-z:

    Random r = new Random();
    char c = (char)(r.nextInt(26) + 'a');
    
    0 讨论(0)
提交回复
热议问题