javaarraysindexoutofboundsexception

How to find every occurrence of a target value in array and return a new array containing the indexes for these values?


I am working on a problem and am having a hard time getting it to output the right information.

What I am trying to do is find every occurrence of a target value and put it into a new array and output the indexes of the target values. If no target value is found it returns an empty array. outputs {}

Right now I am getting an error.

findAll(): 
[I@349b688e
[I@46ed5d9d
java.lang.ArrayIndexOutOfBoundsException

The outputs should be:

outputs {0, 5}

outputs {}

public class FindIndex(){
public FindIndex() {
int a[] = {7, 8, 9, 9, 8, 7};

System.out.println("findAll(): ");
System.out.println(findAll(a, 7));
System.out.print(findAll(a, 2));
}

public int[] findAll(int a[], int num) {

    int indexNum = 0;
    int arrSize = 0;
    
 
    // find all occurrence of the target number
    for(int i = 0; i < a.length; i++) {
        if(a[i] == num) {
            arrSize++;
        }
    }
    
    // create new array 
    int newArray[] = new int[arrSize];
    for(int i = 0; i < a.length; i++) {
        if(a[i] == num) {
            newArray[indexNum] = i;
            
        }
    }
    return newArray;
}

public void print(int a[]) {
    System.out.print("{");
    int i;
    
    for(i = 0; i < a.length - 1; i++) {
        System.out.print(a[i] + ", ");
    }
    
    if(a.length > 0) {
        System.out.print(a[i]);
    }
    System.out.print("}\n");

}
}

Solution

  • You are never incrementing indexNum, it always remains at 0 and the array keeps on writing the values at this same index.

    I think you should have this expression there:

    newArray[indexNum++] = i;