Question

Running this code gives me an array out of bounds exception at the line:

int sum = array[k]+array[l]; //sum of l and k

...Should be a simple fix, but I can't figure out what could be causing it, given I'm using array.length to bound the loop. Can anyone help?

P.S. For the record, this code is supposed to search an int array for pairs of ints or single ints that equal to a target int. It works using solely the println's, but I'm trying to put the numbers that add up to the target into vectors.

public Vector<Vector<Integer>> subsetSum(int[] array, int target) {
    //creates vectors, adds inner vector to another vector
    outer = new Vector<Vector<Integer>>();
    inner = new Vector<Integer>();
    outer.add(inner);

    for (int k = 0; k <= array.length; k++) {
        for (int l = 0; l <= array.length; l++) {
            int sum = array[k]+array[l]; //sum of l and k
            int i = 0;

            if (sum == target) {

                inner.add(i, array[l]);
                inner.add(i, array[k]);

                i++;

                //prints combination
                System.out.println(array[l]+"+"+array[k]+"="+target);
            }
            if (k == target) {
                inner.add(i, array[k]);
                i++;
                //prints if int equals target
                System.out.println(k+"="+target);
            }
            if (l == target) {
                inner.add(i, array[l]);
                i++;
                //prints if int equals target
                System.out.println(l+"="+target);
            }
        }
    }
    //return combinations that add up to target in vector form
    System.out.println(outer);
    return outer;
}
Was it helpful?

Solution

You need to use "<" instead of "<=" in your for loops.

Since the first position in the array is 0, the last position is length-1. What's happening is that when you reach the last iteration, the index is already out of the bounds of the array.

For instance, if you have an array:

array = [0,1,2,3] the last iteration would be array[4], the length of the array, which is out of the bounds.

OTHER TIPS

the <= should be replaced with <

Change your loops to be:

for (int k = 0; k < array.length; k++)

and

for (int l = 0; l < array.length; l++)

Since arrays are 0-based, you want to go 1 less than the length.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top