简体   繁体   English

从数组随机生成的三个特定字母

[英]Three specific letters random generated from array

I really want to make a class that can generate 3 random letters with an array 12 times. 我真的很想创建一个可以生成12个数组的3个随机字母的类。 I'm having some trouble with random requesting int instead of char. 我在随机请求int而不是char时遇到了一些麻烦。 Thanks for help! 感谢帮助! :) :)

First, you need to define an alphabet String alphabet = "AaBb..." , which contains all valid characters. 首先,您需要定义一个字母String alphabet = "AaBb..." ,其中包含所有有效字符。 Then your code can look like this: 然后您的代码如下所示:

public char generateRandomLetterFromAlphabet(String alphabet) {
    Random random = new Random();
    return alphabet.charAt(random.nextInt(alphabet.length()));
}

Here, nextInt(alphabet.length()) returns a random index between zero and the length of the alphabet string, so a random character of your alphabet is returned by generateRandomLetterFromAlphabet . 在这里, nextInt(alphabet.length())返回一个介于零和字母字符串长度之间的随机索引,因此, generateRandomLetterFromAlphabet返回您字母的随机字符。 Note that Random generates pseudo-random numbers. 请注意, Random生成伪随机数。

Of course, your alphabet can be defined by an array, too. 当然,您的字母也可以由数组定义。 Here you have a function to generate a specified number of random characters from an alphabet as character array: 在这里,您可以使用一个函数来从字母表中生成指定数量的随机字符作为字符数组:

public char[] generateRandomLettersFromAlphabet(char[] alphabet,
        int numberOfLetters) {

    if (numberOfLetters < 1) {
        throw new IllegalArgumentException(
                "Number of letters must be strictly positive.");
    }

    Random random = new Random();
    char[] randomLetters = new char[numberOfLetters];

    for (int i = 0; i < numberOfLetters; i++) {
        randomLetters[i] = alphabet[random.nextInt(alphabet.length)];
    }

    return randomLetters;

}

You can use ASCII codes to convert a random integer number to the correspondent char. 您可以使用ASCII码将随机整数转换为对应的char。 More info about ascii at: http://www.ascii-code.com/ 有关ascii的更多信息,请访问: http : //www.ascii-code.com/

This simple method outputs a char based on a random integer between 65 (capital A) and 90 (capital Z). 这种简单的方法基于65(大写A)和90(大写Z)之间的随机整数输出char。

public char randomChar(){
    Random r = new Random();
    int num = r.nextInt(26) + 65;
    return (char) num;
}

Now you can tweak this method to your own purposes. 现在,您可以根据自己的目的调整此方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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