Hello,
It appears that I'm having a slight problem with a pesky ArrayIndexOutOfBoundsException when trying to assign a value to an array embedded within an object. I think it's because the array hasn't been instantiated before I try to add values to it's index.

The purpose of the program is to generate an array of random numbers within each object of the population.
So, in the following case there will be 10 objects each with their own 8 random number sequences.

Firstly, here is a code snippet from my main class.

        int a = 10
        int b = 8

        Random random = new Random();

        //create a population of objects
        Object[] population = new Object[a];
        //create temporary object
        Object currentObject = new Object(b);

        for (int i = 0; i < a; i++) {
            //create a random sequence of numbers within temporary object
            for (int j = 0; j < b; j++) {
                int numberValue = random.nextInt(11);
                currentObject.setValue(j, numberValue);
            }
            population[i] = currentObject;
        }

And secondly, a code snippet from my object.

public class Object {
    int numbValues;
    int[] values = new int[numbValues];

    Object(int numbValues) {
        this.numbValues = numbValues;
    }

    public void setValue (int index, int value) {
        values[index] = value;
    }

    }

Appreciate all help given, thanks in advance.

Recommended Answers

All 2 Replies

int numbValues;  // not initialised, will be zero
int[] values = new int[numbValues];  // array of zero elements, any index will be out of bounds
 Object(int numbValues) {
    this.numbValues = numbValues; // updates numValues, but too late to affect size of array
}

.

Also you can bring the innitializing of the
int[] values = new int[numbValues]; into the constructor.

 Object(int numbValues) {
values = new int[numbValues];
this.numbValues = numbValues;
}

but leave the declaration outside .
that is
`int [] values;'

By this you will be fine also.
that means you will need to called the class with a value new Object(33);

commented: Solved my problem, thanks! +0
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.