In this java sample will show how to generate a random vowel. A vowel is represented in English language by A, E, I, O, U, and sometimes Y. If you are building a guessing game which generates a random character this java or java 8 snippet should help.
Straight up Java
@Test
public void random_vowels_java() {
char[] vowel = { 'a', 'e', 'i', 'o', 'u' };
Random random = new Random(vowel.length);
for (int x = 0; x < 10; x++) {
int arrayElement = random.nextInt(vowel.length);
System.out.println(vowel[arrayElement]);
}
}
Output
i
i
u
u
e
a
u
e
i
e
Java 8
Using a similar technique we saw in how to generate arbitrary lowercase letter we will create a char array with vowels. Next choosing a random number between one and the size of the char array we can pick based on the number chosen. Finally output a stream by using a for loop we will see the results.
@Test
public void generate_random_vowels_java8() {
char[] vowel = { 'a', 'e', 'i', 'o', 'u' };
Random random = new Random(vowel.length);
random.ints(1, vowel.length).limit(10)
.forEach(e -> System.out.println(vowel[e]));
}
Output
o
e
e
o
i
u
i
u
i
i