-1

Please help, still a newbie with java and I have no idea why I keep getting the following error message:

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException

Here is the method I am using:

    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;
    }   

Any tips, or help would be greatly appreciated, I have looked through the method and can't tell why the code is not working.

1 Answers1

0

Java arrays start at 0. So, if you have 6 items in an Array, you only can pic from 0 to 5

So, in order to solve your problem, you have to replace

rand.nextInt(6)

by

rand.nextInt(6)-1
DamCx
  • 1,047
  • 1
  • 11
  • 25
  • 1
    This is not the problem. `rand.nextInt(6)` will never return 6, it will return a random number between 0 and 5 (inclusive). See [API documentation](http://docs.oracle.com/javase/8/docs/api/java/util/Random.html#nextInt-int-). – Jesper Dec 01 '16 at 11:05