Reputation: 39
My Java program requires me to create a random name between 6-12 characters, the odd positions in the name have to be consonants and the even positions have to be vowels, so far I can't even get it to print random 12 letters. The code below in the method brandName() should iterate and keep adding random letters to the string new_Name until it has 12 letters but whenever I run it it only prints one random letter to new_Name. I've been trying ti figure it out for hours.... Code below
public class BrandName {
public static void main(String[] args) {
int name_iterations = 1;
int name_counter = 0;
while (name_iterations <= 10) {
name_counter++;
name_iterations++;
System.out.print("\n" + name_counter +") " + brandName());
}
}
public static String brandName() {
for (int iterations = 0; iterations <= 10; iterations ++); {
String new_Name = "";
int letter_Selector = 24;
int randomChar = (int) (Math.random() * letter_Selector);
String alphabet = "abcdefghijklmniprstuvwxz";
String odd_Consonants = "bcdfghjklmnprstvwxz";
String even_Vowels = "aeiou";
for (int max_Name = 0; max_Name <= 12; max_Name++); {
new_Name = new_Name + (alphabet.charAt(randomChar));
return new_Name;
}
}
}
}
Upvotes: 0
Views: 784
Reputation: 64657
You need to move the initialization of the string out of the loop:
for (int iterations = 0; iterations <= 10; iterations ++); {
String new_Name = "";
to
String new_Name = "";
for (int iterations = 0; iterations <= 10; iterations ++); {
otherwise, each iteration you lose the previous random character from the previous iteration.
And then you need to wait for the loop to complete before returning:
for (int max_Name = 0; max_Name <= 12; max_Name++); {
new_Name = new_Name + (alphabet.charAt(randomChar));
// return new_Name; <-- remove this line
}
return new_Name; // <-- and put it here
And now that I'm looking at it all together, I'm not sure what the iterations
loop is doing, you probably just need to remove that part entirely
public static String brandName() {
String new_Name = "";
int letter_Selector = 24;
String odd_Consonants = "bcdfghjklmnprstvwxz";
String even_Vowels = "aeiou";
int lengthSelector = ThreadLocalRandom.current().nextInt(5, 11 + 1);
for (int max_Name = 0; max_Name <= lengthSelector; max_Name++) {
if (max_Name % 2 == 0) {
int randomChar = (int) (Math.random() * even_Vowels.length());
new_Name = new_Name + (even_Vowels.charAt(randomChar));
} else {
int randomChar = (int) (Math.random() * odd_Consonants.length());
new_Name = new_Name + (odd_Consonants.charAt(randomChar));
}
}
return new_Name;
}
Upvotes: 1