Search for items in an array, and then return a new array with index (s)

advertisements

I would highly appreciate it if someone can point me in the right direction. I am learning Java by following online examples Murach's Java book. I wanted to write a function which takes two arguments:

Arguments:

1: An int myArr
2: An int num

I would like to go through the the "myArr", and find if "num" exists once or more than once within "myArr". So lets say if "myArr" has the "num" lets say in three places, I would like to create a new array within the function, and capture all three indexes within this new array and return the new array. I have been at it for some time now, I think I am getting confused and can use some help.

My issue is that I am uncertain about declaring the new Array size within the function. So lets if "myArr" had 5 elements:

1,2,1,1,4

and if I am searching for number 1, as you can see, number 1 appears more than once within the myArr. So now I need to declare a new array with size of 3 within the function and then push the related indexes (i.e. 0, 2 and 3) to this newly created array and then return it. I am not doing my for loops right and end up with IndexOutOfBoundArray. I appreciate your time and advice.

Here is my code:

public void searchArray(int[] myArr, int num){

    int counter = 0;
    int[] newArr = new int[counter];

    //FOR-LOOP
    for(int i=0; i < myArr.length; i++){
        if(myArr[i] == num){
            counter++;
        }
    }
    // SECOND FOR LOOP
    for(int j=0; j < myArr.length; j++){
      newArr[j] = j;
    }

    // PRING OUT 'newArr' elements
    for(int value : newArr){

        System.out.printf(" %d ", value);
    }
}

Thank you.


Your first mistake is you are creating newArr before calculating counter, so it always create an array of 0 elements.

Other mistake is you are setting newArr values in incorrectly

public void searchArray(int[] myArr, int num){

    int counter = 0;

    //FOR-LOOP
    for(int i=0; i < myArr.length; i++){
        if(myArr[i] == num){
            counter++;
        }
    }

    int[] newArr = new int[counter];

    // SECOND FOR LOOP

    for(int i=0, j=0; i < myArr.length; i++){
        if(myArr[i] == num){
            newArr[j++] = i;
        }
    }

    // PRING OUT 'newArr' elements
    for(int value : newArr){

        System.out.printf(" %d ", value);
    }
}