数组出界?

时间:2016-12-01 11:00:09

标签: java

请帮助,仍然是java的新手,我不知道为什么我一直收到以下错误信息:

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException

以下是我使用的方法:

    public static ArrayList <Animal> createAnimalArrayList() {
        String[] animalName = {"Skye", "Toby", "Peppa", "Charley", "Nemo", "Maisie"};
        String[] ownerName = {"Joe Bloggs", "Mary Rice", "Ann Carroll", "Ciara Roddy", "Lllian Parks", "Ruth Jones"};
        int[] animalAge = {10, 5, 1, 6, 2, 8, 3};
        AnimalType[] animalType = {AnimalType.CAT, AnimalType.COW, AnimalType.DOG, AnimalType.GERBIL, AnimalType.HORSE, AnimalType.SHEEP};

        ArrayList<Animal> animalList = new ArrayList<Animal>();
        Random rand = new Random();
        int randomNum = 0;
        String aName = "";
        String oName = "";
        int aAge = -1;
        AnimalType aType = null;

        int randNumAnimals = rand.nextInt(4)+1;

        for (int i = 0; i<randNumAnimals; i++) {
            aName = animalName[rand.nextInt(6)];
            oName = ownerName[rand.nextInt(6)];
            aAge = animalAge[rand.nextInt(6)];
            aType = animalType[rand.nextInt(6)];
            animalList.add(new Animal(aName, oName, aAge, aType));
        }
        return animalList;
    }   

任何提示或帮助将不胜感激,我已经查看了该方法并且无法分辨为什么代码无效。

1 个答案:

答案 0 :(得分:0)

Java数组从0开始。因此,如果数组中有6个项目,则只能从0到5进行图片

因此,为了解决您的问题,您必须更换

rand.nextInt(6)

通过

rand.nextInt(6)-1