我想從char[] vowel
和char[] consonant
中獲得一個隨機數組值到char[] firstName
和char[] lastName
。如何從java中的一個數組中得到一個隨機值
運行代碼然而,當我的IDE(Eclipse中)顯示
firstName[i]=consonant [random.nextInt(consonant.length)];
沒有錯誤,我會得到錯誤
`Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0 at _01NameGenerator.main(_01NameGenerator.java:27)`
我應如何解決這個說法?
// http://www.javapractices.com/topic/TopicAction.do?Id=62
import java.util.Random;
public class _001NameGenerator {
public static void main(String[] args) {
Random random = new Random();
int firstNameLength = 7; // fixed length, not "random"
int lastNameLength = 5;
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 = new char[firstNameLength];
char[] lastName = new char[lastNameLength];
boolean wechsel = true;
for (int i = 0; i < firstNameLength; i++) {
if (wechsel == true){
firstName[i]=consonant [random.nextInt(20)]; // length of consonant array
wechsel = false;
} else {
firstName[i]=vowel [random.nextInt(6)]; // length of vowel array
wechsel = true;
}
}
for (int i = 0; i < lastNameLength; i++) {
if (wechsel == true){
lastName[i]=consonant [random.nextInt(20)];
wechsel = false;
} else {
lastName[i]=vowel [random.nextInt(6)];
wechsel = true;
}
}
System.out.println(firstName + "\n" + lastName);
}
}
你覺得'char [] someArray = {};'確實如此,你爲什麼認爲你可以用'someArray [0]'的方式使用它?你知道陣列具有固定長度嗎? – Pshemo
嗨pshemo,我不知道固定長度。我只是想讓它初始化。然而,給它'firstNameLenght'的長度不幸並不能解決問題。 – grerrg
其實它解決了這個問題,但顯然你有另一個。那麼現在的錯誤信息是什麼? – Pshemo