February 27th, 2014, 10:31 PM
-
Finding index's of a certain number in an array
I have it done just getting an error.
Code:
int a[] = {7, 8, 9, 9, 8, 7};
I have this array, now what I need to do is call a method that finds a certain number in this array and prints it's INDEX where it is found.
Code:
System.out.println("Finds indes of where this int occurs, returns empty if not found: " + (findAll(a, 7)));
System.out.println("Finds indes of where this int occurs, returns empty if not found: " + (findAll(a, 2)));
Here is the Method
Code:
public int[] findAll(int[] arr, int num){
int count = 0, tracker = 0;
for (int b : arr){
if (b == num)
count++;
}
int result[] = new int[count];
for (int i = 0; i < arr.length; i++){
if (arr[i] == num){
result[tracker] = i; // I think this is the error
tracker++;
}
}
return result;
}
The expected output for 7 should be {0 5}, and for 2, {}
Update: I was just being dumb. I was trying to just return a array for print. I needed to make another method that printed arrays.