Is there functionality to generate a random character in Java?

前端 未结 18 2068
难免孤独
难免孤独 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: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.

提交回复
热议问题