In: Computer Science
I cannot figure out why my random name generator isn't producing the letter u or z. Can someone help me out? The language is java.
import java.util.Random;
public class BrandName {
public static void main(String[] args) {
Random random = new Random();
System.out.println("Brand Name
Generator - Michael Wikstrom\n");
char odd[] = { 'b', 'c', 'd', 'f',
'g', 'h', 'j', 'k', 'l', 'm', 'n', 'p', 'r', 's', 't', 'v', 'w',
'x', 'y',
'z' };
char even[] = { 'a', 'e', 'i', 'o',
'u' };
for (int i = 1; i <= 10; i++) {
int length =
random.nextInt(4) + 8;
String name = "
";
for (int j = 0;
j < length; j++) {
if (j == 0) {
int pos =
random.nextInt(odd.length - 1);
name +=
Character.toUpperCase(odd[pos]);
} else if (j % 2 == 1) {
int pos =
random.nextInt(even.length - 1);
name += even[pos];
} else {
int pos =
random.nextInt(odd.length - 1);
name += odd[pos];
}
}
System.out.println(i + ") " + name);
}
}
}
Please find your solution below and do upvote if doubt comment.
Corrected code:
import java.util.Random;
public class BrandName {
public static void main(String[] args) {
Random random = new Random();
System.out.println("Brand Name Generator - Michael Wikstrom\n");
char odd[] = { 'b', 'c', 'd', 'f', 'g', 'h', 'j', 'k', 'l', 'm', 'n', 'p', 'r', 's', 't', 'v', 'w', 'x', 'y','z' };
char even[] = { 'a', 'e', 'i', 'o', 'u' };
for (int i = 1; i <= 10; i++) {
int length = random.nextInt(4) + 8;
String name = " ";
for (int j = 0; j < length; j++) {
if (j == 0) {
int pos = random.nextInt(odd.length);
name += Character.toUpperCase(odd[pos]);
} else if (j % 2 == 1) {
int pos = random.nextInt(even.length);
name += even[pos];
} else {
int pos = random.nextInt(odd.length);
name += odd[pos];
}
}
System.out.println(i + ") " + name);
}
}
}