简体   繁体   中英

Generating random words of a certain length in java?

I would like to ask another question about how to write a method that generates random words of a certain length and when calling a method user selects the length of words that will be generated and returned from the method. JOptionPane needs to be used for input. The method work needs to be shown through Main.

What kind of words do you want to generate? Random lowercase characters?

String getRandomWord(int length) {
    String r = "";
    for(int i = 0; i < length; i++) {
        r += (char)(Math.random() * 26 + 97);
    }
    return r;
}

Here is a simple way to generate lowercase strings of length characters. The idea is that you randomly add a character using the ASCII table up to the required length.

public static String randomWord(int length) {
    Random random = new Random();
    StringBuilder word = new StringBuilder(length);
    for (int i = 0; i < length; i++) {
        word.append((char)('a' + random.nextInt(26)));
    }

    return word.toString();
}

The easiest way is to use RandomStringUtils class from org.apache.commons.lang3 package. The example below shows you, how it can be used. It will return something like "WYhZXwUQfl", when you pass, for example, 10 to the method.

 public String generateRandomString(int stringLength){
    return RandomStringUtils.randomAlphabetic(stringLength);
}

I encourage you to check this class, because it has many useful methods to generate random strings.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM