如何在java中从一个数组获取随机值到另一个数组

时间:2015-05-15 14:05:17

标签: java arrays random indexoutofboundsexception

我希望从char[] vowelchar[] consonant获取随机数组值到char[] firstNamechar[] 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);

    }

}

4 个答案:

答案 0 :(得分:3)

char[] firstName = {};
char[] lastName = {};

这两行生成空列表,因此每当您尝试添加某些内容时,它都会生成ArrayIndexOutOfBoundsException: 0

由于您具有上述随机长度,请尝试以下方法:

char[] firstName = new char[firstNameLength];
char[] lastName = new char[lastNameLength];

另外,如果您事先不知道数组的长度,可以使用为这些目的而创建的ArrayList。

答案 1 :(得分:1)

您已将firstNamelastName初始化为零长度数组。因此,在第一次迭代时,您尝试将值赋给firstName[0],但“0”是空数组的无效索引,因此是异常。

您应该使用length:

初始化数组
char[] firstName = new char[firstNameLength];
char[] lastName = new char[lastNameLength];

答案 2 :(得分:0)

答案很明显:这两个数组都是零长度:

    char[] firstName = {};
    char[] lastName = {};

答案 3 :(得分:0)

您将firstNamelastName数组声明为空的零长度数组。您应该根据您的代码声明如下:

char[] firstName = new char[firstNameLength];
char[] lastName = new char[lastNameLength];

这可以防止您获得ArrayIndexOutOfBoundsException。