I want to get a random array value from char[] vowel and char[] consonant into char[] firstName and char[] lastName.
My IDE (Eclipse) shows no errors for
firstName[i]=consonant [random.nextInt(consonant.length)];
however when running the code i'll get the error
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0 at _01NameGenerator.main(_01NameGenerator.java:27)
How shall I fix this statement?
import java.util.Random;
public class _01NameGenerator {
public static void main(String[] args) {
Random random = new Random();
int nameMinimum = 3;
int nameRange = 7;
int firstNameLength = nameMinimum + (int) (Math.random()* nameRange); //nameRange suits better than nameMaximum
int lastNameLength = nameMinimum + (int) (Math.random()* nameRange);
System.out.println("Your firstname will be "+firstNameLength+" and you lastname "+lastNameLength+" characters long.");
char[] vowel = {'a', 'e', 'i', 'o', 'u', 'y'};
char[] consonant = {'b', 'c', 'd', 'f', 'g', 'h', 'j', 'k', 'l', 'm', 'n', 'p', 'q', 'r', 's', 't', 'v', 'w', 'x', 'z'};
char[] firstName = {};
char[] lastName = {};
boolean wechsel = true;
for (int i = 0; i < firstNameLength; i++) {
if (wechsel == true){
firstName[i]=consonant [random.nextInt(consonant.length)];
wechsel = false;
} else {
firstName[i]=vowel [random.nextInt(vowel.length)];
wechsel = true;
}
}
for (int i = 0; i < lastNameLength; i++) {
if (wechsel == true){
lastName[i]=consonant [random.nextInt(consonant.length)];
wechsel = false;
} else {
lastName[i]=vowel [random.nextInt(vowel.length)];
wechsel = true;
}
}
System.out.println(firstName + "" + lastName);
}
}
Aucun commentaire:
Enregistrer un commentaire