java - Three specific letters random generated from array -
i want make class can generate 3 random letters array 12 times. i'm having trouble random requesting int instead of char. help! :)
first, need define alphabet string alphabet = "aabb..."
, contains valid characters. code can this:
public char generaterandomletterfromalphabet(string alphabet) { random random = new random(); return alphabet.charat(random.nextint(alphabet.length())); }
here, nextint(alphabet.length())
returns random index between 0 , length of alphabet string, random character of alphabet returned generaterandomletterfromalphabet
. note random
generates pseudo-random numbers.
of course, alphabet can defined array, too. here have function generate specified number of random characters alphabet character array:
public char[] generaterandomlettersfromalphabet(char[] alphabet, int numberofletters) { if (numberofletters < 1) { throw new illegalargumentexception( "number of letters must strictly positive."); } random random = new random(); char[] randomletters = new char[numberofletters]; (int = 0; < numberofletters; i++) { randomletters[i] = alphabet[random.nextint(alphabet.length)]; } return randomletters; }
Comments
Post a Comment