【发布时间】:2015-05-15 14:05:16
【问题描述】:
我想从char[] vowel 和char[] consonant 中获取一个随机数组值到char[] firstName 和char[] lastName。
我的 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,我不知道固定长度。我只是希望它被初始化。然而,不幸的是,给它
firstNameLenght的长度并不能解决问题。 -
其实它解决了这个问题,但显然你还有一个。那么现在的错误信息是什么?
-
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 8 at _01NameGenerator.main(_01NameGenerator.java:27)或Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 8 at _01NameGenerator.main(_01NameGenerator.java:32) -
这意味着您的循环正在尝试访问数组边界之外的元素。尝试适当限制
[i]和[random.nextInt(consonant.length)]的范围(使用适当数组的长度)。
标签: java arrays random indexoutofboundsexception