10) A statement that creates invokes findAll() based on the argument 8 and assigns this to a new array
11) A print statement that prints out the array created in the above step.
Which i did with the following bit of code in my driver

ArrayMethods arrayTwo = new ArrayMethods();

but i am receiving an error from this next bit of code in my class for out of bounds

 public int[]findAll(int key)
        int index = 0;
        int count = 0;
        for(int i : a)
            if(a[i] == key) //this is where the error is being highlighted
        int[]array = new int[count];
        if(count!= 0)
            for(int i=0;i<a.length;i++)
            System.out.println("Key chosen doesnt exist in array");
        return array;

any help with what im doing wrong here would be much appreciated :).

Edited 2 Years Ago by Raymond_3

I believe the problem is your First for loop. The variable i is being set to the value of a[0], then a[1], etc. If a[0] equals 200, you're asking it to check a[200].

What do you mean if a[0] equals 200?
I did forget to mention that the array a[] is defined further up in this class
and is as follows


That was theoretical. What I mean is i is being set to whatever values you have in your array. So the first time through your for loop i will be set to 7, and it will check if a[7] == key, the second time it will check if a[8] == key. Since your array is only 8 long, trying to check a[8] will throw an exception.

Edited 2 Years Ago by John Code

well ive tried revising the code with your help, and im still at the same problem, should i use a for loop instead of a for each?

That should help, or you could write

if (i == key)

instead of

if (a[i] == key)

the first way is for a for each loop, the second is for a normal for loop.

This question has already been answered. Start a new discussion instead.